dsound: Fix refcounting for the secondary buffer object.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include <stdarg.h>
23
24 #define NONAMELESSSTRUCT
25 #define NONAMELESSUNION
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winuser.h"
29 #include "mmsystem.h"
30 #include "winternl.h"
31 #include "vfwmsgs.h"
32 #include "wine/debug.h"
33 #include "dsound.h"
34 #include "dsdriver.h"
35 #include "dsound_private.h"
36 #include "dsconf.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
39
40 /*******************************************************************************
41  *              IDirectSoundNotify
42  */
43
44 struct IDirectSoundNotifyImpl
45 {
46     /* IUnknown fields */
47     const IDirectSoundNotifyVtbl *lpVtbl;
48     LONG                        ref;
49     IDirectSoundBufferImpl*     dsb;
50 };
51
52 static HRESULT IDirectSoundNotifyImpl_Create(IDirectSoundBufferImpl *dsb,
53                                              IDirectSoundNotifyImpl **pdsn);
54 static HRESULT IDirectSoundNotifyImpl_Destroy(IDirectSoundNotifyImpl *pdsn);
55
56 static HRESULT WINAPI IDirectSoundNotifyImpl_QueryInterface(
57         LPDIRECTSOUNDNOTIFY iface,REFIID riid,LPVOID *ppobj
58 ) {
59         IDirectSoundNotifyImpl *This = (IDirectSoundNotifyImpl *)iface;
60         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
61
62         if (This->dsb == NULL) {
63                 WARN("invalid parameter\n");
64                 return E_INVALIDARG;
65         }
66
67         return IDirectSoundBuffer_QueryInterface((LPDIRECTSOUNDBUFFER)This->dsb, riid, ppobj);
68 }
69
70 static ULONG WINAPI IDirectSoundNotifyImpl_AddRef(LPDIRECTSOUNDNOTIFY iface)
71 {
72     IDirectSoundNotifyImpl *This = (IDirectSoundNotifyImpl *)iface;
73     ULONG ref = InterlockedIncrement(&(This->ref));
74     TRACE("(%p) ref was %d\n", This, ref - 1);
75     return ref;
76 }
77
78 static ULONG WINAPI IDirectSoundNotifyImpl_Release(LPDIRECTSOUNDNOTIFY iface)
79 {
80     IDirectSoundNotifyImpl *This = (IDirectSoundNotifyImpl *)iface;
81     ULONG ref = InterlockedDecrement(&(This->ref));
82     TRACE("(%p) ref was %d\n", This, ref + 1);
83
84     if (!ref) {
85         This->dsb->notify = NULL;
86         IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)This->dsb);
87         HeapFree(GetProcessHeap(), 0, This);
88         TRACE("(%p) released\n", This);
89     }
90     return ref;
91 }
92
93 static HRESULT WINAPI IDirectSoundNotifyImpl_SetNotificationPositions(
94         LPDIRECTSOUNDNOTIFY iface,DWORD howmuch,LPCDSBPOSITIONNOTIFY notify
95 ) {
96         IDirectSoundNotifyImpl *This = (IDirectSoundNotifyImpl *)iface;
97         TRACE("(%p,0x%08x,%p)\n",This,howmuch,notify);
98
99         if (howmuch > 0 && notify == NULL) {
100             WARN("invalid parameter: notify == NULL\n");
101             return DSERR_INVALIDPARAM;
102         }
103
104         if (TRACE_ON(dsound)) {
105             unsigned int        i;
106             for (i=0;i<howmuch;i++)
107                 TRACE("notify at %d to %p\n",
108                     notify[i].dwOffset,notify[i].hEventNotify);
109         }
110
111         if (This->dsb->hwnotify) {
112             HRESULT hres;
113             hres = IDsDriverNotify_SetNotificationPositions(This->dsb->hwnotify, howmuch, notify);
114             if (hres != DS_OK)
115                     WARN("IDsDriverNotify_SetNotificationPositions failed\n");
116             return hres;
117         } else if (howmuch > 0) {
118             /* Make an internal copy of the caller-supplied array.
119              * Replace the existing copy if one is already present. */
120             HeapFree(GetProcessHeap(), 0, This->dsb->notifies);
121             This->dsb->notifies = HeapAlloc(GetProcessHeap(), 0,
122                         howmuch * sizeof(DSBPOSITIONNOTIFY));
123
124             if (This->dsb->notifies == NULL) {
125                     WARN("out of memory\n");
126                     return DSERR_OUTOFMEMORY;
127             }
128             CopyMemory(This->dsb->notifies, notify, howmuch * sizeof(DSBPOSITIONNOTIFY));
129             This->dsb->nrofnotifies = howmuch;
130         } else {
131            HeapFree(GetProcessHeap(), 0, This->dsb->notifies);
132            This->dsb->notifies = NULL;
133            This->dsb->nrofnotifies = 0;
134         }
135
136         return S_OK;
137 }
138
139 static const IDirectSoundNotifyVtbl dsnvt =
140 {
141     IDirectSoundNotifyImpl_QueryInterface,
142     IDirectSoundNotifyImpl_AddRef,
143     IDirectSoundNotifyImpl_Release,
144     IDirectSoundNotifyImpl_SetNotificationPositions,
145 };
146
147 static HRESULT IDirectSoundNotifyImpl_Create(
148     IDirectSoundBufferImpl * dsb,
149     IDirectSoundNotifyImpl **pdsn)
150 {
151     IDirectSoundNotifyImpl * dsn;
152     TRACE("(%p,%p)\n",dsb,pdsn);
153
154     dsn = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*dsn));
155
156     if (dsn == NULL) {
157         WARN("out of memory\n");
158         return DSERR_OUTOFMEMORY;
159     }
160
161     dsn->ref = 0;
162     dsn->lpVtbl = &dsnvt;
163     dsn->dsb = dsb;
164     dsb->notify = dsn;
165     IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)dsb);
166
167     *pdsn = dsn;
168     return DS_OK;
169 }
170
171 static HRESULT IDirectSoundNotifyImpl_Destroy(
172     IDirectSoundNotifyImpl *pdsn)
173 {
174     TRACE("(%p)\n",pdsn);
175
176     while (IDirectSoundNotifyImpl_Release((LPDIRECTSOUNDNOTIFY)pdsn) > 0);
177
178     return DS_OK;
179 }
180
181 /*******************************************************************************
182  *              IDirectSoundBuffer
183  */
184
185 static inline IDirectSoundBufferImpl *impl_from_IDirectSoundBuffer8(IDirectSoundBuffer8 *iface)
186 {
187     return CONTAINING_RECORD(iface, IDirectSoundBufferImpl, IDirectSoundBuffer8_iface);
188 }
189
190 static HRESULT WINAPI IDirectSoundBufferImpl_SetFormat(IDirectSoundBuffer8 *iface,
191         LPCWAVEFORMATEX wfex)
192 {
193         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
194
195         TRACE("(%p,%p)\n",This,wfex);
196         /* This method is not available on secondary buffers */
197         WARN("invalid call\n");
198         return DSERR_INVALIDCALL;
199 }
200
201 static HRESULT WINAPI IDirectSoundBufferImpl_SetVolume(IDirectSoundBuffer8 *iface, LONG vol)
202 {
203         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
204         LONG oldVol;
205
206         HRESULT hres = DS_OK;
207
208         TRACE("(%p,%d)\n",This,vol);
209
210         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
211                 WARN("control unavailable: This->dsbd.dwFlags = 0x%08x\n", This->dsbd.dwFlags);
212                 return DSERR_CONTROLUNAVAIL;
213         }
214
215         if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN)) {
216                 WARN("invalid parameter: vol = %d\n", vol);
217                 return DSERR_INVALIDPARAM;
218         }
219
220         /* **** */
221         RtlAcquireResourceExclusive(&This->lock, TRUE);
222
223         if (This->dsbd.dwFlags & DSBCAPS_CTRL3D) {
224                 oldVol = This->ds3db_lVolume;
225                 This->ds3db_lVolume = vol;
226                 if (vol != oldVol)
227                         /* recalc 3d volume, which in turn recalcs the pans */
228                         DSOUND_Calc3DBuffer(This);
229         } else {
230                 oldVol = This->volpan.lVolume;
231                 This->volpan.lVolume = vol;
232                 if (vol != oldVol)
233                         DSOUND_RecalcVolPan(&(This->volpan));
234         }
235
236         if (vol != oldVol) {
237                 if (This->hwbuf) {
238                         hres = IDsDriverBuffer_SetVolumePan(This->hwbuf, &(This->volpan));
239                         if (hres != DS_OK)
240                                 WARN("IDsDriverBuffer_SetVolumePan failed\n");
241                 }
242         }
243
244         RtlReleaseResource(&This->lock);
245         /* **** */
246
247         return hres;
248 }
249
250 static HRESULT WINAPI IDirectSoundBufferImpl_GetVolume(IDirectSoundBuffer8 *iface, LONG *vol)
251 {
252         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
253
254         TRACE("(%p,%p)\n",This,vol);
255
256         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
257                 WARN("control unavailable\n");
258                 return DSERR_CONTROLUNAVAIL;
259         }
260
261         if (vol == NULL) {
262                 WARN("invalid parameter: vol == NULL\n");
263                 return DSERR_INVALIDPARAM;
264         }
265
266         *vol = This->volpan.lVolume;
267
268         return DS_OK;
269 }
270
271 static HRESULT WINAPI IDirectSoundBufferImpl_SetFrequency(IDirectSoundBuffer8 *iface, DWORD freq)
272 {
273         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
274         DWORD oldFreq;
275
276         TRACE("(%p,%d)\n",This,freq);
277
278         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) {
279                 WARN("control unavailable\n");
280                 return DSERR_CONTROLUNAVAIL;
281         }
282
283         if (freq == DSBFREQUENCY_ORIGINAL)
284                 freq = This->pwfx->nSamplesPerSec;
285
286         if ((freq < DSBFREQUENCY_MIN) || (freq > DSBFREQUENCY_MAX)) {
287                 WARN("invalid parameter: freq = %d\n", freq);
288                 return DSERR_INVALIDPARAM;
289         }
290
291         /* **** */
292         RtlAcquireResourceExclusive(&This->lock, TRUE);
293
294         oldFreq = This->freq;
295         This->freq = freq;
296         if (freq != oldFreq) {
297                 This->freqAdjust = ((DWORD64)This->freq << DSOUND_FREQSHIFT) / This->device->pwfx->nSamplesPerSec;
298                 This->nAvgBytesPerSec = freq * This->pwfx->nBlockAlign;
299                 DSOUND_RecalcFormat(This);
300                 DSOUND_MixToTemporary(This, 0, This->buflen, FALSE);
301         }
302
303         RtlReleaseResource(&This->lock);
304         /* **** */
305
306         return DS_OK;
307 }
308
309 static HRESULT WINAPI IDirectSoundBufferImpl_Play(IDirectSoundBuffer8 *iface, DWORD reserved1,
310         DWORD reserved2, DWORD flags)
311 {
312         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
313         HRESULT hres = DS_OK;
314
315         TRACE("(%p,%08x,%08x,%08x)\n",This,reserved1,reserved2,flags);
316
317         /* **** */
318         RtlAcquireResourceExclusive(&This->lock, TRUE);
319
320         This->playflags = flags;
321         if (This->state == STATE_STOPPED && !This->hwbuf) {
322                 This->leadin = TRUE;
323                 This->state = STATE_STARTING;
324         } else if (This->state == STATE_STOPPING)
325                 This->state = STATE_PLAYING;
326         if (This->hwbuf) {
327                 hres = IDsDriverBuffer_Play(This->hwbuf, 0, 0, This->playflags);
328                 if (hres != DS_OK)
329                         WARN("IDsDriverBuffer_Play failed\n");
330                 else
331                         This->state = STATE_PLAYING;
332         }
333
334         RtlReleaseResource(&This->lock);
335         /* **** */
336
337         return hres;
338 }
339
340 static HRESULT WINAPI IDirectSoundBufferImpl_Stop(IDirectSoundBuffer8 *iface)
341 {
342         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
343         HRESULT hres = DS_OK;
344
345         TRACE("(%p)\n",This);
346
347         /* **** */
348         RtlAcquireResourceExclusive(&This->lock, TRUE);
349
350         if (This->state == STATE_PLAYING)
351                 This->state = STATE_STOPPING;
352         else if (This->state == STATE_STARTING)
353         {
354                 This->state = STATE_STOPPED;
355                 DSOUND_CheckEvent(This, 0, 0);
356         }
357         if (This->hwbuf) {
358                 hres = IDsDriverBuffer_Stop(This->hwbuf);
359                 if (hres != DS_OK)
360                         WARN("IDsDriverBuffer_Stop failed\n");
361                 else
362                         This->state = STATE_STOPPED;
363         }
364
365         RtlReleaseResource(&This->lock);
366         /* **** */
367
368         return hres;
369 }
370
371 static ULONG WINAPI IDirectSoundBufferImpl_AddRef(IDirectSoundBuffer8 *iface)
372 {
373     IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
374     ULONG ref = InterlockedIncrement(&This->ref);
375
376     TRACE("(%p) ref was %d\n", This, ref - 1);
377
378     if(ref == 1)
379         InterlockedIncrement(&This->numIfaces);
380
381     return ref;
382 }
383
384 static ULONG WINAPI IDirectSoundBufferImpl_Release(IDirectSoundBuffer8 *iface)
385 {
386     IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
387     ULONG ref = InterlockedDecrement(&This->ref);
388
389     TRACE("(%p) ref was %d\n", This, ref + 1);
390
391     if (!ref && !InterlockedDecrement(&This->numIfaces))
392         secondarybuffer_destroy(This);
393
394     return ref;
395 }
396
397 static HRESULT WINAPI IDirectSoundBufferImpl_GetCurrentPosition(IDirectSoundBuffer8 *iface,
398         DWORD *playpos, DWORD *writepos)
399 {
400         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
401         HRESULT hres;
402
403         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
404
405         RtlAcquireResourceShared(&This->lock, TRUE);
406         if (This->hwbuf) {
407                 hres=IDsDriverBuffer_GetPosition(This->hwbuf,playpos,writepos);
408                 if (hres != DS_OK) {
409                     WARN("IDsDriverBuffer_GetPosition failed\n");
410                     return hres;
411                 }
412         } else {
413                 DWORD pos = This->sec_mixpos;
414
415                 /* sanity */
416                 if (pos >= This->buflen){
417                         FIXME("Bad play position. playpos: %d, buflen: %d\n", pos, This->buflen);
418                         pos %= This->buflen;
419                 }
420
421                 if (playpos)
422                         *playpos = pos;
423                 if (writepos)
424                         *writepos = pos;
425         }
426         if (writepos && This->state != STATE_STOPPED && (!This->hwbuf || !(This->device->drvdesc.dwFlags & DSDDESC_DONTNEEDWRITELEAD))) {
427                 /* apply the documented 10ms lead to writepos */
428                 *writepos += This->writelead;
429                 *writepos %= This->buflen;
430         }
431         RtlReleaseResource(&This->lock);
432
433         TRACE("playpos = %d, writepos = %d, buflen=%d (%p, time=%d)\n",
434                 playpos?*playpos:-1, writepos?*writepos:-1, This->buflen, This, GetTickCount());
435
436         return DS_OK;
437 }
438
439 static HRESULT WINAPI IDirectSoundBufferImpl_GetStatus(IDirectSoundBuffer8 *iface, DWORD *status)
440 {
441         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
442
443         TRACE("(%p,%p), thread is %04x\n",This,status,GetCurrentThreadId());
444
445         if (status == NULL) {
446                 WARN("invalid parameter: status = NULL\n");
447                 return DSERR_INVALIDPARAM;
448         }
449
450         *status = 0;
451         RtlAcquireResourceShared(&This->lock, TRUE);
452         if ((This->state == STATE_STARTING) || (This->state == STATE_PLAYING)) {
453                 *status |= DSBSTATUS_PLAYING;
454                 if (This->playflags & DSBPLAY_LOOPING)
455                         *status |= DSBSTATUS_LOOPING;
456         }
457         RtlReleaseResource(&This->lock);
458
459         TRACE("status=%x\n", *status);
460         return DS_OK;
461 }
462
463
464 static HRESULT WINAPI IDirectSoundBufferImpl_GetFormat(IDirectSoundBuffer8 *iface,
465         LPWAVEFORMATEX lpwf, DWORD wfsize, DWORD *wfwritten)
466 {
467     IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
468     DWORD size;
469
470     TRACE("(%p,%p,%d,%p)\n",This,lpwf,wfsize,wfwritten);
471
472     size = sizeof(WAVEFORMATEX) + This->pwfx->cbSize;
473
474     if (lpwf) { /* NULL is valid */
475         if (wfsize >= size) {
476             CopyMemory(lpwf,This->pwfx,size);
477             if (wfwritten)
478                 *wfwritten = size;
479         } else {
480             WARN("invalid parameter: wfsize too small\n");
481             CopyMemory(lpwf,This->pwfx,wfsize);
482             if (wfwritten)
483                 *wfwritten = wfsize;
484             return DSERR_INVALIDPARAM;
485         }
486     } else {
487         if (wfwritten)
488             *wfwritten = sizeof(WAVEFORMATEX) + This->pwfx->cbSize;
489         else {
490             WARN("invalid parameter: wfwritten == NULL\n");
491             return DSERR_INVALIDPARAM;
492         }
493     }
494
495     return DS_OK;
496 }
497
498 static HRESULT WINAPI IDirectSoundBufferImpl_Lock(IDirectSoundBuffer8 *iface, DWORD writecursor,
499         DWORD writebytes, void **lplpaudioptr1, DWORD *audiobytes1, void **lplpaudioptr2,
500         DWORD *audiobytes2, DWORD flags)
501 {
502         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
503         HRESULT hres = DS_OK;
504
505         TRACE("(%p,%d,%d,%p,%p,%p,%p,0x%08x) at %d\n", This, writecursor, writebytes, lplpaudioptr1,
506                 audiobytes1, lplpaudioptr2, audiobytes2, flags, GetTickCount());
507
508         if (!audiobytes1)
509             return DSERR_INVALIDPARAM;
510
511         /* when this flag is set, writecursor is meaningless and must be calculated */
512         if (flags & DSBLOCK_FROMWRITECURSOR) {
513                 /* GetCurrentPosition does too much magic to duplicate here */
514                 hres = IDirectSoundBufferImpl_GetCurrentPosition(iface, NULL, &writecursor);
515                 if (hres != DS_OK) {
516                         WARN("IDirectSoundBufferImpl_GetCurrentPosition failed\n");
517                         return hres;
518                 }
519         }
520
521         /* when this flag is set, writebytes is meaningless and must be set */
522         if (flags & DSBLOCK_ENTIREBUFFER)
523                 writebytes = This->buflen;
524
525         if (writecursor >= This->buflen) {
526                 WARN("Invalid parameter, writecursor: %u >= buflen: %u\n",
527                      writecursor, This->buflen);
528                 return DSERR_INVALIDPARAM;
529         }
530
531         if (writebytes > This->buflen) {
532                 WARN("Invalid parameter, writebytes: %u > buflen: %u\n",
533                      writebytes, This->buflen);
534                 return DSERR_INVALIDPARAM;
535         }
536
537         /* **** */
538         RtlAcquireResourceShared(&This->lock, TRUE);
539
540         if (!(This->device->drvdesc.dwFlags & DSDDESC_DONTNEEDSECONDARYLOCK) && This->hwbuf) {
541                 hres = IDsDriverBuffer_Lock(This->hwbuf,
542                                      lplpaudioptr1, audiobytes1,
543                                      lplpaudioptr2, audiobytes2,
544                                      writecursor, writebytes,
545                                      0);
546                 if (hres != DS_OK) {
547                         WARN("IDsDriverBuffer_Lock failed\n");
548                         RtlReleaseResource(&This->lock);
549                         return hres;
550                 }
551         } else {
552                 if (writecursor+writebytes <= This->buflen) {
553                         *(LPBYTE*)lplpaudioptr1 = This->buffer->memory+writecursor;
554                         if (This->sec_mixpos >= writecursor && This->sec_mixpos < writecursor + writebytes && This->state == STATE_PLAYING)
555                                 WARN("Overwriting mixing position, case 1\n");
556                         *audiobytes1 = writebytes;
557                         if (lplpaudioptr2)
558                                 *(LPBYTE*)lplpaudioptr2 = NULL;
559                         if (audiobytes2)
560                                 *audiobytes2 = 0;
561                         TRACE("Locked %p(%i bytes) and %p(%i bytes) writecursor=%d\n",
562                           *(LPBYTE*)lplpaudioptr1, *audiobytes1, lplpaudioptr2 ? *(LPBYTE*)lplpaudioptr2 : NULL, audiobytes2 ? *audiobytes2: 0, writecursor);
563                         TRACE("->%d.0\n",writebytes);
564                 } else {
565                         DWORD remainder = writebytes + writecursor - This->buflen;
566                         *(LPBYTE*)lplpaudioptr1 = This->buffer->memory+writecursor;
567                         *audiobytes1 = This->buflen-writecursor;
568                         if (This->sec_mixpos >= writecursor && This->sec_mixpos < writecursor + writebytes && This->state == STATE_PLAYING)
569                                 WARN("Overwriting mixing position, case 2\n");
570                         if (lplpaudioptr2)
571                                 *(LPBYTE*)lplpaudioptr2 = This->buffer->memory;
572                         if (audiobytes2)
573                                 *audiobytes2 = writebytes-(This->buflen-writecursor);
574                         if (audiobytes2 && This->sec_mixpos < remainder && This->state == STATE_PLAYING)
575                                 WARN("Overwriting mixing position, case 3\n");
576                         TRACE("Locked %p(%i bytes) and %p(%i bytes) writecursor=%d\n", *(LPBYTE*)lplpaudioptr1, *audiobytes1, lplpaudioptr2 ? *(LPBYTE*)lplpaudioptr2 : NULL, audiobytes2 ? *audiobytes2: 0, writecursor);
577                 }
578         }
579
580         RtlReleaseResource(&This->lock);
581         /* **** */
582
583         return DS_OK;
584 }
585
586 static HRESULT WINAPI IDirectSoundBufferImpl_SetCurrentPosition(IDirectSoundBuffer8 *iface,
587         DWORD newpos)
588 {
589         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
590         HRESULT hres = DS_OK;
591         DWORD oldpos;
592
593         TRACE("(%p,%d)\n",This,newpos);
594
595         /* **** */
596         RtlAcquireResourceExclusive(&This->lock, TRUE);
597
598         oldpos = This->sec_mixpos;
599
600         /* start mixing from this new location instead */
601         newpos %= This->buflen;
602         newpos -= newpos%This->pwfx->nBlockAlign;
603         This->sec_mixpos = newpos;
604
605         /* at this point, do not attempt to reset buffers, mess with primary mix position,
606            or anything like that to reduce latency. The data already prebuffered cannot be changed */
607
608         /* position HW buffer if applicable, else just start mixing from new location instead */
609         if (This->hwbuf) {
610                 hres = IDsDriverBuffer_SetPosition(This->hwbuf, This->buf_mixpos);
611                 if (hres != DS_OK)
612                         WARN("IDsDriverBuffer_SetPosition failed\n");
613         }
614         else if (oldpos != newpos)
615                 /* FIXME: Perhaps add a call to DSOUND_MixToTemporary here? Not sure it's needed */
616                 This->buf_mixpos = DSOUND_secpos_to_bufpos(This, newpos, 0, NULL);
617
618         RtlReleaseResource(&This->lock);
619         /* **** */
620
621         return hres;
622 }
623
624 static HRESULT WINAPI IDirectSoundBufferImpl_SetPan(IDirectSoundBuffer8 *iface, LONG pan)
625 {
626         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
627         HRESULT hres = DS_OK;
628
629         TRACE("(%p,%d)\n",This,pan);
630
631         if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT)) {
632                 WARN("invalid parameter: pan = %d\n", pan);
633                 return DSERR_INVALIDPARAM;
634         }
635
636         /* You cannot use both pan and 3D controls */
637         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
638             (This->dsbd.dwFlags & DSBCAPS_CTRL3D)) {
639                 WARN("control unavailable\n");
640                 return DSERR_CONTROLUNAVAIL;
641         }
642
643         /* **** */
644         RtlAcquireResourceExclusive(&This->lock, TRUE);
645
646         if (This->volpan.lPan != pan) {
647                 This->volpan.lPan = pan;
648                 DSOUND_RecalcVolPan(&(This->volpan));
649
650                 if (This->hwbuf) {
651                         hres = IDsDriverBuffer_SetVolumePan(This->hwbuf, &(This->volpan));
652                         if (hres != DS_OK)
653                                 WARN("IDsDriverBuffer_SetVolumePan failed\n");
654                 }
655         }
656
657         RtlReleaseResource(&This->lock);
658         /* **** */
659
660         return hres;
661 }
662
663 static HRESULT WINAPI IDirectSoundBufferImpl_GetPan(IDirectSoundBuffer8 *iface, LONG *pan)
664 {
665         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
666
667         TRACE("(%p,%p)\n",This,pan);
668
669         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
670                 WARN("control unavailable\n");
671                 return DSERR_CONTROLUNAVAIL;
672         }
673
674         if (pan == NULL) {
675                 WARN("invalid parameter: pan = NULL\n");
676                 return DSERR_INVALIDPARAM;
677         }
678
679         *pan = This->volpan.lPan;
680
681         return DS_OK;
682 }
683
684 static HRESULT WINAPI IDirectSoundBufferImpl_Unlock(IDirectSoundBuffer8 *iface, void *p1, DWORD x1,
685         void *p2, DWORD x2)
686 {
687         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface), *iter;
688         HRESULT hres = DS_OK;
689
690         TRACE("(%p,%p,%d,%p,%d)\n", This,p1,x1,p2,x2);
691
692         /* **** */
693         RtlAcquireResourceShared(&This->lock, TRUE);
694
695         if (!(This->device->drvdesc.dwFlags & DSDDESC_DONTNEEDSECONDARYLOCK) && This->hwbuf) {
696                 hres = IDsDriverBuffer_Unlock(This->hwbuf, p1, x1, p2, x2);
697                 if (hres != DS_OK)
698                         WARN("IDsDriverBuffer_Unlock failed\n");
699         }
700
701         RtlReleaseResource(&This->lock);
702         /* **** */
703
704         if (!p2)
705                 x2 = 0;
706
707         if (!This->hwbuf && (x1 || x2))
708         {
709                 RtlAcquireResourceShared(&This->device->buffer_list_lock, TRUE);
710                 LIST_FOR_EACH_ENTRY(iter, &This->buffer->buffers, IDirectSoundBufferImpl, entry )
711                 {
712                         RtlAcquireResourceShared(&iter->lock, TRUE);
713                         if (x1)
714                         {
715                             if(x1 + (DWORD_PTR)p1 - (DWORD_PTR)iter->buffer->memory > iter->buflen)
716                               hres = DSERR_INVALIDPARAM;
717                             else
718                               DSOUND_MixToTemporary(iter, (DWORD_PTR)p1 - (DWORD_PTR)iter->buffer->memory, x1, FALSE);
719                         }
720                         if (x2)
721                                 DSOUND_MixToTemporary(iter, 0, x2, FALSE);
722                         RtlReleaseResource(&iter->lock);
723                 }
724                 RtlReleaseResource(&This->device->buffer_list_lock);
725         }
726
727         return hres;
728 }
729
730 static HRESULT WINAPI IDirectSoundBufferImpl_Restore(IDirectSoundBuffer8 *iface)
731 {
732         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
733
734         FIXME("(%p):stub\n",This);
735         return DS_OK;
736 }
737
738 static HRESULT WINAPI IDirectSoundBufferImpl_GetFrequency(IDirectSoundBuffer8 *iface, DWORD *freq)
739 {
740         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
741
742         TRACE("(%p,%p)\n",This,freq);
743
744         if (freq == NULL) {
745                 WARN("invalid parameter: freq = NULL\n");
746                 return DSERR_INVALIDPARAM;
747         }
748
749         *freq = This->freq;
750         TRACE("-> %d\n", *freq);
751
752         return DS_OK;
753 }
754
755 static HRESULT WINAPI IDirectSoundBufferImpl_SetFX(IDirectSoundBuffer8 *iface, DWORD dwEffectsCount,
756         LPDSEFFECTDESC pDSFXDesc, DWORD *pdwResultCodes)
757 {
758         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
759         DWORD u;
760
761         FIXME("(%p,%u,%p,%p): stub\n",This,dwEffectsCount,pDSFXDesc,pdwResultCodes);
762
763         if (pdwResultCodes)
764                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
765
766         WARN("control unavailable\n");
767         return DSERR_CONTROLUNAVAIL;
768 }
769
770 static HRESULT WINAPI IDirectSoundBufferImpl_AcquireResources(IDirectSoundBuffer8 *iface,
771         DWORD dwFlags, DWORD dwEffectsCount, DWORD *pdwResultCodes)
772 {
773         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
774         DWORD u;
775
776         FIXME("(%p,%08u,%u,%p): stub, faking success\n",This,dwFlags,dwEffectsCount,pdwResultCodes);
777
778         if (pdwResultCodes)
779                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
780
781         WARN("control unavailable\n");
782         return DS_OK;
783 }
784
785 static HRESULT WINAPI IDirectSoundBufferImpl_GetObjectInPath(IDirectSoundBuffer8 *iface,
786         REFGUID rguidObject, DWORD dwIndex, REFGUID rguidInterface, void **ppObject)
787 {
788         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
789
790         FIXME("(%p,%s,%u,%s,%p): stub\n",This,debugstr_guid(rguidObject),dwIndex,debugstr_guid(rguidInterface),ppObject);
791
792         WARN("control unavailable\n");
793         return DSERR_CONTROLUNAVAIL;
794 }
795
796 static HRESULT WINAPI IDirectSoundBufferImpl_Initialize(IDirectSoundBuffer8 *iface,
797         IDirectSound *dsound, LPCDSBUFFERDESC dbsd)
798 {
799         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
800
801         WARN("(%p) already initialized\n", This);
802         return DSERR_ALREADYINITIALIZED;
803 }
804
805 static HRESULT WINAPI IDirectSoundBufferImpl_GetCaps(IDirectSoundBuffer8 *iface, LPDSBCAPS caps)
806 {
807         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
808
809         TRACE("(%p)->(%p)\n",This,caps);
810
811         if (caps == NULL) {
812                 WARN("invalid parameter: caps == NULL\n");
813                 return DSERR_INVALIDPARAM;
814         }
815
816         if (caps->dwSize < sizeof(*caps)) {
817                 WARN("invalid parameter: caps->dwSize = %d\n",caps->dwSize);
818                 return DSERR_INVALIDPARAM;
819         }
820
821         caps->dwFlags = This->dsbd.dwFlags;
822         if (This->hwbuf) caps->dwFlags |= DSBCAPS_LOCHARDWARE;
823         else caps->dwFlags |= DSBCAPS_LOCSOFTWARE;
824
825         caps->dwBufferBytes = This->buflen;
826
827         /* According to windows, this is zero*/
828         caps->dwUnlockTransferRate = 0;
829         caps->dwPlayCpuOverhead = 0;
830
831         return DS_OK;
832 }
833
834 static HRESULT WINAPI IDirectSoundBufferImpl_QueryInterface(IDirectSoundBuffer8 *iface, REFIID riid,
835         void **ppobj)
836 {
837         IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
838
839         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
840
841         if (ppobj == NULL) {
842                 WARN("invalid parameter\n");
843                 return E_INVALIDARG;
844         }
845
846         *ppobj = NULL;  /* assume failure */
847
848         if ( IsEqualGUID(riid, &IID_IUnknown) ||
849              IsEqualGUID(riid, &IID_IDirectSoundBuffer) ||
850              IsEqualGUID(riid, &IID_IDirectSoundBuffer8) ) {
851                 IDirectSoundBuffer8_AddRef(iface);
852                 *ppobj = iface;
853                 return S_OK;
854         }
855
856         if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
857                 if (!This->notify)
858                         IDirectSoundNotifyImpl_Create(This, &(This->notify));
859                 if (This->notify) {
860                         IDirectSoundNotify_AddRef((LPDIRECTSOUNDNOTIFY)This->notify);
861                         *ppobj = This->notify;
862                         return S_OK;
863                 }
864                 WARN("IID_IDirectSoundNotify\n");
865                 return E_NOINTERFACE;
866         }
867
868         if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
869                 if (!This->ds3db)
870                         IDirectSound3DBufferImpl_Create(This, &(This->ds3db));
871                 if (This->ds3db) {
872                         IDirectSound3DBuffer_AddRef((LPDIRECTSOUND3DBUFFER)This->ds3db);
873                         *ppobj = This->ds3db;
874                         return S_OK;
875                 }
876                 WARN("IID_IDirectSound3DBuffer\n");
877                 return E_NOINTERFACE;
878         }
879
880         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
881                 ERR("app requested IDirectSound3DListener on secondary buffer\n");
882                 return E_NOINTERFACE;
883         }
884
885         if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
886                 if (!This->iks)
887                         IKsBufferPropertySetImpl_Create(This, &(This->iks));
888                 if (This->iks) {
889                         IKsPropertySet_AddRef((LPKSPROPERTYSET)This->iks);
890                         *ppobj = This->iks;
891                         return S_OK;
892                 }
893                 WARN("IID_IKsPropertySet\n");
894                 return E_NOINTERFACE;
895         }
896
897         FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
898
899         return E_NOINTERFACE;
900 }
901
902 static const IDirectSoundBuffer8Vtbl dsbvt =
903 {
904         IDirectSoundBufferImpl_QueryInterface,
905         IDirectSoundBufferImpl_AddRef,
906         IDirectSoundBufferImpl_Release,
907         IDirectSoundBufferImpl_GetCaps,
908         IDirectSoundBufferImpl_GetCurrentPosition,
909         IDirectSoundBufferImpl_GetFormat,
910         IDirectSoundBufferImpl_GetVolume,
911         IDirectSoundBufferImpl_GetPan,
912         IDirectSoundBufferImpl_GetFrequency,
913         IDirectSoundBufferImpl_GetStatus,
914         IDirectSoundBufferImpl_Initialize,
915         IDirectSoundBufferImpl_Lock,
916         IDirectSoundBufferImpl_Play,
917         IDirectSoundBufferImpl_SetCurrentPosition,
918         IDirectSoundBufferImpl_SetFormat,
919         IDirectSoundBufferImpl_SetVolume,
920         IDirectSoundBufferImpl_SetPan,
921         IDirectSoundBufferImpl_SetFrequency,
922         IDirectSoundBufferImpl_Stop,
923         IDirectSoundBufferImpl_Unlock,
924         IDirectSoundBufferImpl_Restore,
925         IDirectSoundBufferImpl_SetFX,
926         IDirectSoundBufferImpl_AcquireResources,
927         IDirectSoundBufferImpl_GetObjectInPath
928 };
929
930 HRESULT IDirectSoundBufferImpl_Create(
931         DirectSoundDevice * device,
932         IDirectSoundBufferImpl **pdsb,
933         LPCDSBUFFERDESC dsbd)
934 {
935         IDirectSoundBufferImpl *dsb;
936         LPWAVEFORMATEX wfex = dsbd->lpwfxFormat;
937         HRESULT err = DS_OK;
938         DWORD capf = 0;
939         int use_hw;
940         TRACE("(%p,%p,%p)\n",device,pdsb,dsbd);
941
942         if (dsbd->dwBufferBytes < DSBSIZE_MIN || dsbd->dwBufferBytes > DSBSIZE_MAX) {
943                 WARN("invalid parameter: dsbd->dwBufferBytes = %d\n", dsbd->dwBufferBytes);
944                 *pdsb = NULL;
945                 return DSERR_INVALIDPARAM; /* FIXME: which error? */
946         }
947
948         dsb = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*dsb));
949
950         if (dsb == 0) {
951                 WARN("out of memory\n");
952                 *pdsb = NULL;
953                 return DSERR_OUTOFMEMORY;
954         }
955
956         TRACE("Created buffer at %p\n", dsb);
957
958         dsb->ref = 1;
959         dsb->numIfaces = 1;
960         dsb->device = device;
961         dsb->IDirectSoundBuffer8_iface.lpVtbl = &dsbvt;
962         dsb->iks = NULL;
963
964         /* size depends on version */
965         CopyMemory(&dsb->dsbd, dsbd, dsbd->dwSize);
966
967         dsb->pwfx = DSOUND_CopyFormat(wfex);
968         if (dsb->pwfx == NULL) {
969                 HeapFree(GetProcessHeap(),0,dsb);
970                 *pdsb = NULL;
971                 return DSERR_OUTOFMEMORY;
972         }
973
974         if (dsbd->dwBufferBytes % dsbd->lpwfxFormat->nBlockAlign)
975                 dsb->buflen = dsbd->dwBufferBytes + 
976                         (dsbd->lpwfxFormat->nBlockAlign - 
977                         (dsbd->dwBufferBytes % dsbd->lpwfxFormat->nBlockAlign));
978         else
979                 dsb->buflen = dsbd->dwBufferBytes;
980
981         dsb->freq = dsbd->lpwfxFormat->nSamplesPerSec;
982         dsb->notify = NULL;
983         dsb->notifies = NULL;
984         dsb->nrofnotifies = 0;
985         dsb->hwnotify = 0;
986
987         /* Check necessary hardware mixing capabilities */
988         if (wfex->nChannels==2) capf |= DSCAPS_SECONDARYSTEREO;
989         else capf |= DSCAPS_SECONDARYMONO;
990         if (wfex->wBitsPerSample==16) capf |= DSCAPS_SECONDARY16BIT;
991         else capf |= DSCAPS_SECONDARY8BIT;
992
993         use_hw = !!(dsbd->dwFlags & DSBCAPS_LOCHARDWARE);
994         TRACE("use_hw = %d, capf = 0x%08x, device->drvcaps.dwFlags = 0x%08x\n", use_hw, capf, device->drvcaps.dwFlags);
995         if (use_hw && ((device->drvcaps.dwFlags & capf) != capf || !device->driver))
996         {
997                 if (device->driver)
998                         WARN("Format not supported for hardware buffer\n");
999                 HeapFree(GetProcessHeap(),0,dsb->pwfx);
1000                 HeapFree(GetProcessHeap(),0,dsb);
1001                 *pdsb = NULL;
1002                 if ((device->drvcaps.dwFlags & capf) != capf)
1003                         return DSERR_BADFORMAT;
1004                 return DSERR_GENERIC;
1005         }
1006
1007         /* FIXME: check hardware sample rate mixing capabilities */
1008         /* FIXME: check app hints for software/hardware buffer (STATIC, LOCHARDWARE, etc) */
1009         /* FIXME: check whether any hardware buffers are left */
1010         /* FIXME: handle DSDHEAP_CREATEHEAP for hardware buffers */
1011
1012         /* Allocate an empty buffer */
1013         dsb->buffer = HeapAlloc(GetProcessHeap(),0,sizeof(*(dsb->buffer)));
1014         if (dsb->buffer == NULL) {
1015                 WARN("out of memory\n");
1016                 HeapFree(GetProcessHeap(),0,dsb->pwfx);
1017                 HeapFree(GetProcessHeap(),0,dsb);
1018                 *pdsb = NULL;
1019                 return DSERR_OUTOFMEMORY;
1020         }
1021
1022         /* Allocate system memory for buffer if applicable */
1023         if ((device->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY) || !use_hw) {
1024                 dsb->buffer->memory = HeapAlloc(GetProcessHeap(),0,dsb->buflen);
1025                 if (dsb->buffer->memory == NULL) {
1026                         WARN("out of memory\n");
1027                         HeapFree(GetProcessHeap(),0,dsb->pwfx);
1028                         HeapFree(GetProcessHeap(),0,dsb->buffer);
1029                         HeapFree(GetProcessHeap(),0,dsb);
1030                         *pdsb = NULL;
1031                         return DSERR_OUTOFMEMORY;
1032                 }
1033         }
1034
1035         /* Allocate the hardware buffer */
1036         if (use_hw) {
1037                 err = IDsDriver_CreateSoundBuffer(device->driver,wfex,dsbd->dwFlags,0,
1038                                                   &(dsb->buflen),&(dsb->buffer->memory),
1039                                                   (LPVOID*)&(dsb->hwbuf));
1040                 if (FAILED(err))
1041                 {
1042                         WARN("Failed to create hardware secondary buffer: %08x\n", err);
1043                         if (device->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY)
1044                                 HeapFree(GetProcessHeap(),0,dsb->buffer->memory);
1045                         HeapFree(GetProcessHeap(),0,dsb->buffer);
1046                         HeapFree(GetProcessHeap(),0,dsb->pwfx);
1047                         HeapFree(GetProcessHeap(),0,dsb);
1048                         *pdsb = NULL;
1049                         return DSERR_GENERIC;
1050                 }
1051         }
1052
1053         dsb->buffer->ref = 1;
1054         list_init(&dsb->buffer->buffers);
1055         list_add_head(&dsb->buffer->buffers, &dsb->entry);
1056         FillMemory(dsb->buffer->memory, dsb->buflen, dsbd->lpwfxFormat->wBitsPerSample == 8 ? 128 : 0);
1057
1058         /* It's not necessary to initialize values to zero since */
1059         /* we allocated this structure with HEAP_ZERO_MEMORY... */
1060         dsb->buf_mixpos = dsb->sec_mixpos = 0;
1061         dsb->state = STATE_STOPPED;
1062
1063         dsb->freqAdjust = ((DWORD64)dsb->freq << DSOUND_FREQSHIFT) / device->pwfx->nSamplesPerSec;
1064         dsb->nAvgBytesPerSec = dsb->freq *
1065                 dsbd->lpwfxFormat->nBlockAlign;
1066
1067         /* calculate fragment size and write lead */
1068         DSOUND_RecalcFormat(dsb);
1069
1070         if (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D) {
1071                 dsb->ds3db_ds3db.dwSize = sizeof(DS3DBUFFER);
1072                 dsb->ds3db_ds3db.vPosition.x = 0.0;
1073                 dsb->ds3db_ds3db.vPosition.y = 0.0;
1074                 dsb->ds3db_ds3db.vPosition.z = 0.0;
1075                 dsb->ds3db_ds3db.vVelocity.x = 0.0;
1076                 dsb->ds3db_ds3db.vVelocity.y = 0.0;
1077                 dsb->ds3db_ds3db.vVelocity.z = 0.0;
1078                 dsb->ds3db_ds3db.dwInsideConeAngle = DS3D_DEFAULTCONEANGLE;
1079                 dsb->ds3db_ds3db.dwOutsideConeAngle = DS3D_DEFAULTCONEANGLE;
1080                 dsb->ds3db_ds3db.vConeOrientation.x = 0.0;
1081                 dsb->ds3db_ds3db.vConeOrientation.y = 0.0;
1082                 dsb->ds3db_ds3db.vConeOrientation.z = 0.0;
1083                 dsb->ds3db_ds3db.lConeOutsideVolume = DS3D_DEFAULTCONEOUTSIDEVOLUME;
1084                 dsb->ds3db_ds3db.flMinDistance = DS3D_DEFAULTMINDISTANCE;
1085                 dsb->ds3db_ds3db.flMaxDistance = DS3D_DEFAULTMAXDISTANCE;
1086                 dsb->ds3db_ds3db.dwMode = DS3DMODE_NORMAL;
1087
1088                 dsb->ds3db_need_recalc = FALSE;
1089                 DSOUND_Calc3DBuffer(dsb);
1090         } else
1091                 DSOUND_RecalcVolPan(&(dsb->volpan));
1092
1093         RtlInitializeResource(&dsb->lock);
1094
1095         /* register buffer if not primary */
1096         if (!(dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER)) {
1097                 err = DirectSoundDevice_AddBuffer(device, dsb);
1098                 if (err != DS_OK) {
1099                         HeapFree(GetProcessHeap(),0,dsb->buffer->memory);
1100                         HeapFree(GetProcessHeap(),0,dsb->buffer);
1101                         RtlDeleteResource(&dsb->lock);
1102                         HeapFree(GetProcessHeap(),0,dsb->pwfx);
1103                         HeapFree(GetProcessHeap(),0,dsb);
1104                         dsb = NULL;
1105                 }
1106         }
1107
1108         *pdsb = dsb;
1109         return err;
1110 }
1111
1112 void secondarybuffer_destroy(IDirectSoundBufferImpl *This)
1113 {
1114     DirectSoundDevice_RemoveBuffer(This->device, This);
1115     RtlDeleteResource(&This->lock);
1116
1117     if (This->hwbuf)
1118         IDsDriverBuffer_Release(This->hwbuf);
1119     if (!This->hwbuf || (This->device->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY)) {
1120         This->buffer->ref--;
1121         list_remove(&This->entry);
1122         if (This->buffer->ref == 0) {
1123             HeapFree(GetProcessHeap(), 0, This->buffer->memory);
1124             HeapFree(GetProcessHeap(), 0, This->buffer);
1125         }
1126     }
1127
1128     HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
1129     HeapFree(GetProcessHeap(), 0, This->notifies);
1130     HeapFree(GetProcessHeap(), 0, This->pwfx);
1131     HeapFree(GetProcessHeap(), 0, This);
1132
1133     TRACE("(%p) released\n", This);
1134 }
1135
1136 HRESULT IDirectSoundBufferImpl_Destroy(
1137     IDirectSoundBufferImpl *pdsb)
1138 {
1139     TRACE("(%p)\n",pdsb);
1140
1141     /* This keeps the *_Destroy functions from possibly deleting
1142      * this object until it is ready to be deleted */
1143     InterlockedIncrement(&pdsb->numIfaces);
1144
1145     if (pdsb->iks) {
1146         WARN("iks not NULL\n");
1147         IKsBufferPropertySetImpl_Destroy(pdsb->iks);
1148         pdsb->iks = NULL;
1149     }
1150
1151     if (pdsb->ds3db) {
1152         WARN("ds3db not NULL\n");
1153         IDirectSound3DBufferImpl_Destroy(pdsb->ds3db);
1154         pdsb->ds3db = NULL;
1155     }
1156
1157     if (pdsb->notify) {
1158         WARN("notify not NULL\n");
1159         IDirectSoundNotifyImpl_Destroy(pdsb->notify);
1160         pdsb->notify = NULL;
1161     }
1162
1163     secondarybuffer_destroy(pdsb);
1164
1165     return S_OK;
1166 }
1167
1168 HRESULT IDirectSoundBufferImpl_Duplicate(
1169     DirectSoundDevice *device,
1170     IDirectSoundBufferImpl **ppdsb,
1171     IDirectSoundBufferImpl *pdsb)
1172 {
1173     IDirectSoundBufferImpl *dsb;
1174     HRESULT hres = DS_OK;
1175     TRACE("(%p,%p,%p)\n", device, ppdsb, pdsb);
1176
1177     dsb = HeapAlloc(GetProcessHeap(),0,sizeof(*dsb));
1178     if (dsb == NULL) {
1179         WARN("out of memory\n");
1180         *ppdsb = NULL;
1181         return DSERR_OUTOFMEMORY;
1182     }
1183     CopyMemory(dsb, pdsb, sizeof(*dsb));
1184
1185     dsb->pwfx = DSOUND_CopyFormat(pdsb->pwfx);
1186     if (dsb->pwfx == NULL) {
1187         HeapFree(GetProcessHeap(),0,dsb);
1188         *ppdsb = NULL;
1189         return DSERR_OUTOFMEMORY;
1190     }
1191
1192     if (pdsb->hwbuf) {
1193         TRACE("duplicating hardware buffer\n");
1194
1195         hres = IDsDriver_DuplicateSoundBuffer(device->driver, pdsb->hwbuf,
1196                                               (LPVOID *)&dsb->hwbuf);
1197         if (FAILED(hres)) {
1198             WARN("IDsDriver_DuplicateSoundBuffer failed (%08x)\n", hres);
1199             HeapFree(GetProcessHeap(),0,dsb->pwfx);
1200             HeapFree(GetProcessHeap(),0,dsb);
1201             *ppdsb = NULL;
1202             return hres;
1203         }
1204     }
1205
1206     dsb->buffer->ref++;
1207     list_add_head(&dsb->buffer->buffers, &dsb->entry);
1208     dsb->ref = 1;
1209     dsb->numIfaces = 1;
1210     dsb->state = STATE_STOPPED;
1211     dsb->buf_mixpos = dsb->sec_mixpos = 0;
1212     dsb->notify = NULL;
1213     dsb->notifies = NULL;
1214     dsb->nrofnotifies = 0;
1215     dsb->device = device;
1216     dsb->ds3db = NULL;
1217     dsb->iks = NULL; /* FIXME? */
1218     dsb->tmp_buffer = NULL;
1219     DSOUND_RecalcFormat(dsb);
1220     DSOUND_MixToTemporary(dsb, 0, dsb->buflen, FALSE);
1221
1222     RtlInitializeResource(&dsb->lock);
1223
1224     /* register buffer */
1225     hres = DirectSoundDevice_AddBuffer(device, dsb);
1226     if (hres != DS_OK) {
1227         RtlDeleteResource(&dsb->lock);
1228         HeapFree(GetProcessHeap(),0,dsb->tmp_buffer);
1229         list_remove(&dsb->entry);
1230         dsb->buffer->ref--;
1231         HeapFree(GetProcessHeap(),0,dsb->pwfx);
1232         HeapFree(GetProcessHeap(),0,dsb);
1233         dsb = NULL;
1234     }
1235
1236     *ppdsb = dsb;
1237     return hres;
1238 }
1239
1240 /*******************************************************************************
1241  *              IKsBufferPropertySet
1242  */
1243
1244 /* IUnknown methods */
1245 static HRESULT WINAPI IKsBufferPropertySetImpl_QueryInterface(
1246     LPKSPROPERTYSET iface,
1247     REFIID riid,
1248     LPVOID *ppobj )
1249 {
1250     IKsBufferPropertySetImpl *This = (IKsBufferPropertySetImpl *)iface;
1251     TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
1252
1253     return IDirectSoundBuffer_QueryInterface((LPDIRECTSOUNDBUFFER8)This->dsb, riid, ppobj);
1254 }
1255
1256 static ULONG WINAPI IKsBufferPropertySetImpl_AddRef(LPKSPROPERTYSET iface)
1257 {
1258     IKsBufferPropertySetImpl *This = (IKsBufferPropertySetImpl *)iface;
1259     ULONG ref = InterlockedIncrement(&(This->ref));
1260     TRACE("(%p) ref was %d\n", This, ref - 1);
1261     return ref;
1262 }
1263
1264 static ULONG WINAPI IKsBufferPropertySetImpl_Release(LPKSPROPERTYSET iface)
1265 {
1266     IKsBufferPropertySetImpl *This = (IKsBufferPropertySetImpl *)iface;
1267     ULONG ref = InterlockedDecrement(&(This->ref));
1268     TRACE("(%p) ref was %d\n", This, ref + 1);
1269
1270     if (!ref) {
1271     This->dsb->iks = 0;
1272     IDirectSoundBuffer_Release((LPDIRECTSOUND3DBUFFER)This->dsb);
1273     HeapFree(GetProcessHeap(), 0, This);
1274     TRACE("(%p) released\n", This);
1275     }
1276     return ref;
1277 }
1278
1279 static HRESULT WINAPI IKsBufferPropertySetImpl_Get(
1280     LPKSPROPERTYSET iface,
1281     REFGUID guidPropSet,
1282     ULONG dwPropID,
1283     LPVOID pInstanceData,
1284     ULONG cbInstanceData,
1285     LPVOID pPropData,
1286     ULONG cbPropData,
1287     PULONG pcbReturned )
1288 {
1289     IKsBufferPropertySetImpl *This = (IKsBufferPropertySetImpl *)iface;
1290     PIDSDRIVERPROPERTYSET ps;
1291     TRACE("(iface=%p,guidPropSet=%s,dwPropID=%d,pInstanceData=%p,cbInstanceData=%d,pPropData=%p,cbPropData=%d,pcbReturned=%p)\n",
1292     This,debugstr_guid(guidPropSet),dwPropID,pInstanceData,cbInstanceData,pPropData,cbPropData,pcbReturned);
1293
1294     if (This->dsb->hwbuf) {
1295         IDsDriver_QueryInterface(This->dsb->hwbuf, &IID_IDsDriverPropertySet, (void **)&ps);
1296
1297         if (ps) {
1298         DSPROPERTY prop;
1299         HRESULT hres;
1300
1301         prop.s.Set = *guidPropSet;
1302         prop.s.Id = dwPropID;
1303         prop.s.Flags = 0;  /* unused */
1304         prop.s.InstanceId = (ULONG)This->dsb->device;
1305
1306
1307         hres = IDsDriverPropertySet_Get(ps, &prop, pInstanceData, cbInstanceData, pPropData, cbPropData, pcbReturned);
1308
1309         IDsDriverPropertySet_Release(ps);
1310
1311         return hres;
1312         }
1313     }
1314
1315     return E_PROP_ID_UNSUPPORTED;
1316 }
1317
1318 static HRESULT WINAPI IKsBufferPropertySetImpl_Set(
1319     LPKSPROPERTYSET iface,
1320     REFGUID guidPropSet,
1321     ULONG dwPropID,
1322     LPVOID pInstanceData,
1323     ULONG cbInstanceData,
1324     LPVOID pPropData,
1325     ULONG cbPropData )
1326 {
1327     IKsBufferPropertySetImpl *This = (IKsBufferPropertySetImpl *)iface;
1328     PIDSDRIVERPROPERTYSET ps;
1329     TRACE("(%p,%s,%d,%p,%d,%p,%d)\n",This,debugstr_guid(guidPropSet),dwPropID,pInstanceData,cbInstanceData,pPropData,cbPropData);
1330
1331     if (This->dsb->hwbuf) {
1332         IDsDriver_QueryInterface(This->dsb->hwbuf, &IID_IDsDriverPropertySet, (void **)&ps);
1333
1334         if (ps) {
1335         DSPROPERTY prop;
1336         HRESULT hres;
1337
1338         prop.s.Set = *guidPropSet;
1339         prop.s.Id = dwPropID;
1340         prop.s.Flags = 0;  /* unused */
1341         prop.s.InstanceId = (ULONG)This->dsb->device;
1342         hres = IDsDriverPropertySet_Set(ps,&prop,pInstanceData,cbInstanceData,pPropData,cbPropData);
1343
1344         IDsDriverPropertySet_Release(ps);
1345
1346         return hres;
1347         }
1348     }
1349
1350     return E_PROP_ID_UNSUPPORTED;
1351 }
1352
1353 static HRESULT WINAPI IKsBufferPropertySetImpl_QuerySupport(
1354     LPKSPROPERTYSET iface,
1355     REFGUID guidPropSet,
1356     ULONG dwPropID,
1357     PULONG pTypeSupport )
1358 {
1359     IKsBufferPropertySetImpl *This = (IKsBufferPropertySetImpl *)iface;
1360     PIDSDRIVERPROPERTYSET ps;
1361     TRACE("(%p,%s,%d,%p)\n",This,debugstr_guid(guidPropSet),dwPropID,pTypeSupport);
1362
1363     if (This->dsb->hwbuf) {
1364         IDsDriver_QueryInterface(This->dsb->hwbuf, &IID_IDsDriverPropertySet, (void **)&ps);
1365
1366         if (ps) {
1367             HRESULT hres;
1368
1369             hres = IDsDriverPropertySet_QuerySupport(ps,guidPropSet, dwPropID,pTypeSupport);
1370
1371             IDsDriverPropertySet_Release(ps);
1372
1373             return hres;
1374         }
1375     }
1376
1377     return E_PROP_ID_UNSUPPORTED;
1378 }
1379
1380 static const IKsPropertySetVtbl iksbvt = {
1381     IKsBufferPropertySetImpl_QueryInterface,
1382     IKsBufferPropertySetImpl_AddRef,
1383     IKsBufferPropertySetImpl_Release,
1384     IKsBufferPropertySetImpl_Get,
1385     IKsBufferPropertySetImpl_Set,
1386     IKsBufferPropertySetImpl_QuerySupport
1387 };
1388
1389 HRESULT IKsBufferPropertySetImpl_Create(
1390     IDirectSoundBufferImpl *dsb,
1391     IKsBufferPropertySetImpl **piks)
1392 {
1393     IKsBufferPropertySetImpl *iks;
1394     TRACE("(%p,%p)\n",dsb,piks);
1395     *piks = NULL;
1396
1397     iks = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*iks));
1398     if (iks == 0) {
1399         WARN("out of memory\n");
1400         *piks = NULL;
1401         return DSERR_OUTOFMEMORY;
1402     }
1403
1404     iks->ref = 0;
1405     iks->dsb = dsb;
1406     dsb->iks = iks;
1407     iks->lpVtbl = &iksbvt;
1408
1409     IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)dsb);
1410
1411     *piks = iks;
1412     return S_OK;
1413 }
1414
1415 HRESULT IKsBufferPropertySetImpl_Destroy(
1416     IKsBufferPropertySetImpl *piks)
1417 {
1418     TRACE("(%p)\n",piks);
1419
1420     while (IKsBufferPropertySetImpl_Release((LPKSPROPERTYSET)piks) > 0);
1421
1422     return S_OK;
1423 }