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