richedit: Avoid rewrapping all text for isolated format changes.
[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 "wine/debug.h"
32 #include "dsound.h"
33 #include "dsdriver.h"
34 #include "dsound_private.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
37
38 static HRESULT SecondaryBufferImpl_Destroy(SecondaryBufferImpl *pdsb);
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         IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)This->dsb);
86         This->dsb->notify = NULL;
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             if (This->dsb->notifies)
121                     This->dsb->notifies = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
122                         This->dsb->notifies, howmuch * sizeof(DSBPOSITIONNOTIFY));
123             else
124                     This->dsb->notifies = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
125                         howmuch * sizeof(DSBPOSITIONNOTIFY));
126
127             if (This->dsb->notifies == NULL) {
128                     WARN("out of memory\n");
129                     return DSERR_OUTOFMEMORY;
130             }
131             CopyMemory(This->dsb->notifies, notify, howmuch * sizeof(DSBPOSITIONNOTIFY));
132             This->dsb->nrofnotifies = howmuch;
133         } else {
134            HeapFree(GetProcessHeap(), 0, This->dsb->notifies);
135            This->dsb->notifies = NULL;
136            This->dsb->nrofnotifies = 0;
137         }
138
139         return S_OK;
140 }
141
142 static const IDirectSoundNotifyVtbl dsnvt =
143 {
144     IDirectSoundNotifyImpl_QueryInterface,
145     IDirectSoundNotifyImpl_AddRef,
146     IDirectSoundNotifyImpl_Release,
147     IDirectSoundNotifyImpl_SetNotificationPositions,
148 };
149
150 static HRESULT IDirectSoundNotifyImpl_Create(
151     IDirectSoundBufferImpl * dsb,
152     IDirectSoundNotifyImpl **pdsn)
153 {
154     IDirectSoundNotifyImpl * dsn;
155     TRACE("(%p,%p)\n",dsb,pdsn);
156
157     dsn = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*dsn));
158
159     if (dsn == NULL) {
160         WARN("out of memory\n");
161         return DSERR_OUTOFMEMORY;
162     }
163
164     dsn->ref = 0;
165     dsn->lpVtbl = &dsnvt;
166     dsn->dsb = dsb;
167     dsb->notify = dsn;
168     IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)dsb);
169
170     *pdsn = dsn;
171     return DS_OK;
172 }
173
174 static HRESULT IDirectSoundNotifyImpl_Destroy(
175     IDirectSoundNotifyImpl *pdsn)
176 {
177     TRACE("(%p)\n",pdsn);
178
179     while (IDirectSoundNotifyImpl_Release((LPDIRECTSOUNDNOTIFY)pdsn) > 0);
180
181     return DS_OK;
182 }
183
184 /*******************************************************************************
185  *              IDirectSoundBuffer
186  */
187
188 static HRESULT WINAPI IDirectSoundBufferImpl_SetFormat(
189         LPDIRECTSOUNDBUFFER8 iface,LPCWAVEFORMATEX wfex
190 ) {
191         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
192
193         TRACE("(%p,%p)\n",This,wfex);
194         /* This method is not available on secondary buffers */
195         WARN("invalid call\n");
196         return DSERR_INVALIDCALL;
197 }
198
199 static HRESULT WINAPI IDirectSoundBufferImpl_SetVolume(
200         LPDIRECTSOUNDBUFFER8 iface,LONG vol
201 ) {
202         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
203         LONG oldVol;
204         HRESULT hres = DS_OK;
205
206         TRACE("(%p,%d)\n",This,vol);
207
208         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
209                 WARN("control unavailable: This->dsbd.dwFlags = 0x%08x\n", This->dsbd.dwFlags);
210                 return DSERR_CONTROLUNAVAIL;
211         }
212
213         if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN)) {
214                 WARN("invalid parameter: vol = %d\n", vol);
215                 return DSERR_INVALIDPARAM;
216         }
217
218         /* **** */
219         RtlAcquireResourceExclusive(&This->lock, TRUE);
220
221         if (This->dsbd.dwFlags & DSBCAPS_CTRL3D) {
222                 oldVol = This->ds3db_lVolume;
223                 This->ds3db_lVolume = vol;
224                 if (vol != oldVol)
225                         /* recalc 3d volume, which in turn recalcs the pans */
226                         DSOUND_Calc3DBuffer(This);
227         } else {
228                 oldVol = This->volpan.lVolume;
229                 This->volpan.lVolume = vol;
230                 if (vol != oldVol)
231                         DSOUND_RecalcVolPan(&(This->volpan));
232         }
233
234         if (vol != oldVol) {
235                 if (This->hwbuf) {
236                         hres = IDsDriverBuffer_SetVolumePan(This->hwbuf, &(This->volpan));
237                         if (hres != DS_OK)
238                                 WARN("IDsDriverBuffer_SetVolumePan failed\n");
239                 }
240         }
241
242         RtlReleaseResource(&This->lock);
243         /* **** */
244
245         return hres;
246 }
247
248 static HRESULT WINAPI IDirectSoundBufferImpl_GetVolume(
249         LPDIRECTSOUNDBUFFER8 iface,LPLONG vol
250 ) {
251         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
252         TRACE("(%p,%p)\n",This,vol);
253
254         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
255                 WARN("control unavailable\n");
256                 return DSERR_CONTROLUNAVAIL;
257         }
258
259         if (vol == NULL) {
260                 WARN("invalid parameter: vol == NULL\n");
261                 return DSERR_INVALIDPARAM;
262         }
263
264         *vol = This->volpan.lVolume;
265
266         return DS_OK;
267 }
268
269 static HRESULT WINAPI IDirectSoundBufferImpl_SetFrequency(
270         LPDIRECTSOUNDBUFFER8 iface,DWORD freq
271 ) {
272         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
273         DWORD oldFreq;
274
275         TRACE("(%p,%d)\n",This,freq);
276
277         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) {
278                 WARN("control unavailable\n");
279                 return DSERR_CONTROLUNAVAIL;
280         }
281
282         if (freq == DSBFREQUENCY_ORIGINAL)
283                 freq = This->pwfx->nSamplesPerSec;
284
285         if ((freq < DSBFREQUENCY_MIN) || (freq > DSBFREQUENCY_MAX)) {
286                 WARN("invalid parameter: freq = %d\n", freq);
287                 return DSERR_INVALIDPARAM;
288         }
289
290         /* **** */
291         RtlAcquireResourceExclusive(&This->lock, TRUE);
292
293         oldFreq = This->freq;
294         This->freq = freq;
295         if (freq != oldFreq) {
296                 This->freqAdjust = ((DWORD64)This->freq << DSOUND_FREQSHIFT) / This->device->pwfx->nSamplesPerSec;
297                 This->nAvgBytesPerSec = freq * This->pwfx->nBlockAlign;
298                 DSOUND_RecalcFormat(This);
299                 DSOUND_MixToTemporary(This, 0, This->buflen, FALSE);
300         }
301
302         RtlReleaseResource(&This->lock);
303         /* **** */
304
305         return DS_OK;
306 }
307
308 static HRESULT WINAPI IDirectSoundBufferImpl_Play(
309         LPDIRECTSOUNDBUFFER8 iface,DWORD reserved1,DWORD reserved2,DWORD flags
310 ) {
311         HRESULT hres = DS_OK;
312         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
313         TRACE("(%p,%08x,%08x,%08x)\n",This,reserved1,reserved2,flags);
314
315         /* **** */
316         RtlAcquireResourceExclusive(&This->lock, TRUE);
317
318         This->playflags = flags;
319         if (This->state == STATE_STOPPED && !This->hwbuf) {
320                 This->leadin = TRUE;
321                 This->state = STATE_STARTING;
322         } else if (This->state == STATE_STOPPING)
323                 This->state = STATE_PLAYING;
324         if (This->hwbuf) {
325                 hres = IDsDriverBuffer_Play(This->hwbuf, 0, 0, This->playflags);
326                 if (hres != DS_OK)
327                         WARN("IDsDriverBuffer_Play failed\n");
328                 else
329                         This->state = STATE_PLAYING;
330         }
331
332         RtlReleaseResource(&This->lock);
333         /* **** */
334
335         return hres;
336 }
337
338 static HRESULT WINAPI IDirectSoundBufferImpl_Stop(LPDIRECTSOUNDBUFFER8 iface)
339 {
340         HRESULT hres = DS_OK;
341         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
342         TRACE("(%p)\n",This);
343
344         /* **** */
345         RtlAcquireResourceExclusive(&This->lock, TRUE);
346
347         if (This->state == STATE_PLAYING)
348                 This->state = STATE_STOPPING;
349         else if (This->state == STATE_STARTING)
350         {
351                 This->state = STATE_STOPPED;
352                 DSOUND_CheckEvent(This, 0, 0);
353         }
354         if (This->hwbuf) {
355                 hres = IDsDriverBuffer_Stop(This->hwbuf);
356                 if (hres != DS_OK)
357                         WARN("IDsDriverBuffer_Stop failed\n");
358                 else
359                         This->state = STATE_STOPPED;
360         }
361
362         RtlReleaseResource(&This->lock);
363         /* **** */
364
365         return hres;
366 }
367
368 static ULONG WINAPI IDirectSoundBufferImpl_AddRef(LPDIRECTSOUNDBUFFER8 iface)
369 {
370     IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
371     ULONG ref = InterlockedIncrement(&(This->ref));
372     TRACE("(%p) ref was %d\n", This, ref - 1);
373     return ref;
374 }
375
376 static ULONG WINAPI IDirectSoundBufferImpl_Release(LPDIRECTSOUNDBUFFER8 iface)
377 {
378     IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
379     ULONG ref = InterlockedDecrement(&(This->ref));
380     TRACE("(%p) ref was %d\n", This, ref + 1);
381
382     if (!ref) {
383         DirectSoundDevice_RemoveBuffer(This->device, This);
384         RtlDeleteResource(&This->lock);
385
386         if (This->hwbuf) {
387                 IDsDriverBuffer_Release(This->hwbuf);
388                 if (This->device->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY) {
389                         This->buffer->ref--;
390                         list_remove(&This->entry);
391                         if (This->buffer->ref==0) {
392                                 HeapFree(GetProcessHeap(),0,This->buffer->memory);
393                                 HeapFree(GetProcessHeap(),0,This->buffer);
394                         }
395                 }
396         } else {
397                 This->buffer->ref--;
398                 list_remove(&This->entry);
399                 if (This->buffer->ref==0) {
400                         HeapFree(GetProcessHeap(),0,This->buffer->memory);
401                         HeapFree(GetProcessHeap(),0,This->buffer);
402                 }
403         }
404
405         HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
406         HeapFree(GetProcessHeap(), 0, This->notifies);
407         HeapFree(GetProcessHeap(), 0, This->pwfx);
408         HeapFree(GetProcessHeap(), 0, This);
409
410         TRACE("(%p) released\n", This);
411     }
412     return ref;
413 }
414
415 static HRESULT WINAPI IDirectSoundBufferImpl_GetCurrentPosition(
416         LPDIRECTSOUNDBUFFER8 iface,LPDWORD playpos,LPDWORD writepos
417 ) {
418         HRESULT hres;
419         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
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(
457         LPDIRECTSOUNDBUFFER8 iface,LPDWORD status
458 ) {
459         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
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(
482     LPDIRECTSOUNDBUFFER8 iface,
483     LPWAVEFORMATEX lpwf,
484     DWORD wfsize,
485     LPDWORD wfwritten)
486 {
487     DWORD size;
488     IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
489     TRACE("(%p,%p,%d,%p)\n",This,lpwf,wfsize,wfwritten);
490
491     size = sizeof(WAVEFORMATEX) + This->pwfx->cbSize;
492
493     if (lpwf) { /* NULL is valid */
494         if (wfsize >= size) {
495             CopyMemory(lpwf,This->pwfx,size);
496             if (wfwritten)
497                 *wfwritten = size;
498         } else {
499             WARN("invalid parameter: wfsize too small\n");
500             CopyMemory(lpwf,This->pwfx,wfsize);
501             if (wfwritten)
502                 *wfwritten = wfsize;
503             return DSERR_INVALIDPARAM;
504         }
505     } else {
506         if (wfwritten)
507             *wfwritten = sizeof(WAVEFORMATEX) + This->pwfx->cbSize;
508         else {
509             WARN("invalid parameter: wfwritten == NULL\n");
510             return DSERR_INVALIDPARAM;
511         }
512     }
513
514     return DS_OK;
515 }
516
517 static HRESULT WINAPI IDirectSoundBufferImpl_Lock(
518         LPDIRECTSOUNDBUFFER8 iface,DWORD writecursor,DWORD writebytes,LPVOID *lplpaudioptr1,LPDWORD audiobytes1,LPVOID *lplpaudioptr2,LPDWORD audiobytes2,DWORD flags
519 ) {
520         HRESULT hres = DS_OK;
521         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
522
523         TRACE("(%p,%d,%d,%p,%p,%p,%p,0x%08x) at %d\n",
524                 This,
525                 writecursor,
526                 writebytes,
527                 lplpaudioptr1,
528                 audiobytes1,
529                 lplpaudioptr2,
530                 audiobytes2,
531                 flags,
532                 GetTickCount()
533         );
534
535         if (!audiobytes1)
536             return DSERR_INVALIDPARAM;
537
538         /* when this flag is set, writecursor is meaningless and must be calculated */
539         if (flags & DSBLOCK_FROMWRITECURSOR) {
540                 /* GetCurrentPosition does too much magic to duplicate here */
541                 hres = IDirectSoundBufferImpl_GetCurrentPosition(iface, NULL, &writecursor);
542                 if (hres != DS_OK) {
543                         WARN("IDirectSoundBufferImpl_GetCurrentPosition failed\n");
544                         return hres;
545                 }
546         }
547
548         /* when this flag is set, writebytes is meaningless and must be set */
549         if (flags & DSBLOCK_ENTIREBUFFER)
550                 writebytes = This->buflen;
551
552         if (writecursor >= This->buflen) {
553                 WARN("Invalid parameter, writecursor: %u >= buflen: %u\n",
554                      writecursor, This->buflen);
555                 return DSERR_INVALIDPARAM;
556         }
557
558         if (writebytes > This->buflen) {
559                 WARN("Invalid parameter, writebytes: %u > buflen: %u\n",
560                      writebytes, This->buflen);
561                 return DSERR_INVALIDPARAM;
562         }
563
564         /* **** */
565         RtlAcquireResourceShared(&This->lock, TRUE);
566
567         if (!(This->device->drvdesc.dwFlags & DSDDESC_DONTNEEDSECONDARYLOCK) && This->hwbuf) {
568                 hres = IDsDriverBuffer_Lock(This->hwbuf,
569                                      lplpaudioptr1, audiobytes1,
570                                      lplpaudioptr2, audiobytes2,
571                                      writecursor, writebytes,
572                                      0);
573                 if (hres != DS_OK) {
574                         WARN("IDsDriverBuffer_Lock failed\n");
575                         RtlReleaseResource(&This->lock);
576                         return hres;
577                 }
578         } else {
579                 if (writecursor+writebytes <= This->buflen) {
580                         *(LPBYTE*)lplpaudioptr1 = This->buffer->memory+writecursor;
581                         if (This->sec_mixpos >= writecursor && This->sec_mixpos < writecursor + writebytes && This->state == STATE_PLAYING)
582                                 WARN("Overwriting mixing position, case 1\n");
583                         *audiobytes1 = writebytes;
584                         if (lplpaudioptr2)
585                                 *(LPBYTE*)lplpaudioptr2 = NULL;
586                         if (audiobytes2)
587                                 *audiobytes2 = 0;
588                         TRACE("Locked %p(%i bytes) and %p(%i bytes) writecursor=%d\n",
589                           *(LPBYTE*)lplpaudioptr1, *audiobytes1, lplpaudioptr2 ? *(LPBYTE*)lplpaudioptr2 : NULL, audiobytes2 ? *audiobytes2: 0, writecursor);
590                         TRACE("->%d.0\n",writebytes);
591                 } else {
592                         DWORD remainder = writebytes + writecursor - This->buflen;
593                         *(LPBYTE*)lplpaudioptr1 = This->buffer->memory+writecursor;
594                         *audiobytes1 = This->buflen-writecursor;
595                         if (This->sec_mixpos >= writecursor && This->sec_mixpos < writecursor + writebytes && This->state == STATE_PLAYING)
596                                 WARN("Overwriting mixing position, case 2\n");
597                         if (lplpaudioptr2)
598                                 *(LPBYTE*)lplpaudioptr2 = This->buffer->memory;
599                         if (audiobytes2)
600                                 *audiobytes2 = writebytes-(This->buflen-writecursor);
601                         if (audiobytes2 && This->sec_mixpos < remainder && This->state == STATE_PLAYING)
602                                 WARN("Overwriting mixing position, case 3\n");
603                         TRACE("Locked %p(%i bytes) and %p(%i bytes) writecursor=%d\n", *(LPBYTE*)lplpaudioptr1, *audiobytes1, lplpaudioptr2 ? *(LPBYTE*)lplpaudioptr2 : NULL, audiobytes2 ? *audiobytes2: 0, writecursor);
604                 }
605         }
606
607         RtlReleaseResource(&This->lock);
608         /* **** */
609
610         return DS_OK;
611 }
612
613 static HRESULT WINAPI IDirectSoundBufferImpl_SetCurrentPosition(
614         LPDIRECTSOUNDBUFFER8 iface,DWORD newpos
615 ) {
616         HRESULT hres = DS_OK;
617         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
618         DWORD oldpos;
619         TRACE("(%p,%d)\n",This,newpos);
620
621         /* **** */
622         RtlAcquireResourceExclusive(&This->lock, TRUE);
623
624         oldpos = This->sec_mixpos;
625
626         /* start mixing from this new location instead */
627         newpos %= This->buflen;
628         newpos -= newpos%This->pwfx->nBlockAlign;
629         This->sec_mixpos = newpos;
630
631         /* at this point, do not attempt to reset buffers, mess with primary mix position,
632            or anything like that to reduce latancy. The data already prebuffered cannot be changed */
633
634         /* position HW buffer if applicable, else just start mixing from new location instead */
635         if (This->hwbuf) {
636                 hres = IDsDriverBuffer_SetPosition(This->hwbuf, This->buf_mixpos);
637                 if (hres != DS_OK)
638                         WARN("IDsDriverBuffer_SetPosition failed\n");
639         }
640         else if (oldpos != newpos)
641                 /* FIXME: Perhaps add a call to DSOUND_MixToTemporary here? Not sure it's needed */
642                 This->buf_mixpos = DSOUND_secpos_to_bufpos(This, newpos, 0, NULL);
643
644         RtlReleaseResource(&This->lock);
645         /* **** */
646
647         return hres;
648 }
649
650 static HRESULT WINAPI IDirectSoundBufferImpl_SetPan(
651         LPDIRECTSOUNDBUFFER8 iface,LONG pan
652 ) {
653         HRESULT hres = DS_OK;
654         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
655
656         TRACE("(%p,%d)\n",This,pan);
657
658         if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT)) {
659                 WARN("invalid parameter: pan = %d\n", pan);
660                 return DSERR_INVALIDPARAM;
661         }
662
663         /* You cannot use both pan and 3D controls */
664         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
665             (This->dsbd.dwFlags & DSBCAPS_CTRL3D)) {
666                 WARN("control unavailable\n");
667                 return DSERR_CONTROLUNAVAIL;
668         }
669
670         /* **** */
671         RtlAcquireResourceExclusive(&This->lock, TRUE);
672
673         if (This->volpan.lPan != pan) {
674                 This->volpan.lPan = pan;
675                 DSOUND_RecalcVolPan(&(This->volpan));
676
677                 if (This->hwbuf) {
678                         hres = IDsDriverBuffer_SetVolumePan(This->hwbuf, &(This->volpan));
679                         if (hres != DS_OK)
680                                 WARN("IDsDriverBuffer_SetVolumePan failed\n");
681                 }
682         }
683
684         RtlReleaseResource(&This->lock);
685         /* **** */
686
687         return hres;
688 }
689
690 static HRESULT WINAPI IDirectSoundBufferImpl_GetPan(
691         LPDIRECTSOUNDBUFFER8 iface,LPLONG pan
692 ) {
693         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
694         TRACE("(%p,%p)\n",This,pan);
695
696         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
697                 WARN("control unavailable\n");
698                 return DSERR_CONTROLUNAVAIL;
699         }
700
701         if (pan == NULL) {
702                 WARN("invalid parameter: pan = NULL\n");
703                 return DSERR_INVALIDPARAM;
704         }
705
706         *pan = This->volpan.lPan;
707
708         return DS_OK;
709 }
710
711 static HRESULT WINAPI IDirectSoundBufferImpl_Unlock(
712         LPDIRECTSOUNDBUFFER8 iface,LPVOID p1,DWORD x1,LPVOID p2,DWORD x2
713 ) {
714         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface, *iter;
715         HRESULT hres = DS_OK;
716
717         TRACE("(%p,%p,%d,%p,%d)\n", This,p1,x1,p2,x2);
718
719         /* **** */
720         RtlAcquireResourceShared(&This->lock, TRUE);
721
722         if (!(This->device->drvdesc.dwFlags & DSDDESC_DONTNEEDSECONDARYLOCK) && This->hwbuf) {
723                 hres = IDsDriverBuffer_Unlock(This->hwbuf, p1, x1, p2, x2);
724                 if (hres != DS_OK)
725                         WARN("IDsDriverBuffer_Unlock failed\n");
726         }
727
728         RtlReleaseResource(&This->lock);
729         /* **** */
730
731         if (!p2)
732                 x2 = 0;
733
734         if (!This->hwbuf && (x1 || x2))
735         {
736                 RtlAcquireResourceShared(&This->device->buffer_list_lock, TRUE);
737                 LIST_FOR_EACH_ENTRY(iter, &This->buffer->buffers, IDirectSoundBufferImpl, entry )
738                 {
739                         RtlAcquireResourceShared(&iter->lock, TRUE);
740                         if (x1)
741                         {
742                             if(x1 + (DWORD_PTR)p1 - (DWORD_PTR)iter->buffer->memory > iter->buflen)
743                               hres = DSERR_INVALIDPARAM;
744                             else
745                               DSOUND_MixToTemporary(iter, (DWORD_PTR)p1 - (DWORD_PTR)iter->buffer->memory, x1, FALSE);
746                         }
747                         if (x2)
748                                 DSOUND_MixToTemporary(iter, 0, x2, FALSE);
749                         RtlReleaseResource(&iter->lock);
750                 }
751                 RtlReleaseResource(&This->device->buffer_list_lock);
752         }
753
754         return hres;
755 }
756
757 static HRESULT WINAPI IDirectSoundBufferImpl_Restore(
758         LPDIRECTSOUNDBUFFER8 iface
759 ) {
760         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
761         FIXME("(%p):stub\n",This);
762         return DS_OK;
763 }
764
765 static HRESULT WINAPI IDirectSoundBufferImpl_GetFrequency(
766         LPDIRECTSOUNDBUFFER8 iface,LPDWORD freq
767 ) {
768         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
769         TRACE("(%p,%p)\n",This,freq);
770
771         if (freq == NULL) {
772                 WARN("invalid parameter: freq = NULL\n");
773                 return DSERR_INVALIDPARAM;
774         }
775
776         *freq = This->freq;
777         TRACE("-> %d\n", *freq);
778
779         return DS_OK;
780 }
781
782 static HRESULT WINAPI IDirectSoundBufferImpl_SetFX(
783         LPDIRECTSOUNDBUFFER8 iface,DWORD dwEffectsCount,LPDSEFFECTDESC pDSFXDesc,LPDWORD pdwResultCodes
784 ) {
785         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
786         DWORD u;
787
788         FIXME("(%p,%u,%p,%p): stub\n",This,dwEffectsCount,pDSFXDesc,pdwResultCodes);
789
790         if (pdwResultCodes)
791                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
792
793         WARN("control unavailable\n");
794         return DSERR_CONTROLUNAVAIL;
795 }
796
797 static HRESULT WINAPI IDirectSoundBufferImpl_AcquireResources(
798         LPDIRECTSOUNDBUFFER8 iface,DWORD dwFlags,DWORD dwEffectsCount,LPDWORD pdwResultCodes
799 ) {
800         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
801         DWORD u;
802
803         FIXME("(%p,%08u,%u,%p): stub\n",This,dwFlags,dwEffectsCount,pdwResultCodes);
804
805         if (pdwResultCodes)
806                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
807
808         WARN("control unavailable\n");
809         return DSERR_CONTROLUNAVAIL;
810 }
811
812 static HRESULT WINAPI IDirectSoundBufferImpl_GetObjectInPath(
813         LPDIRECTSOUNDBUFFER8 iface,REFGUID rguidObject,DWORD dwIndex,REFGUID rguidInterface,LPVOID* ppObject
814 ) {
815         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
816
817         FIXME("(%p,%s,%u,%s,%p): stub\n",This,debugstr_guid(rguidObject),dwIndex,debugstr_guid(rguidInterface),ppObject);
818
819         WARN("control unavailable\n");
820         return DSERR_CONTROLUNAVAIL;
821 }
822
823 static HRESULT WINAPI IDirectSoundBufferImpl_Initialize(
824         LPDIRECTSOUNDBUFFER8 iface,LPDIRECTSOUND dsound,LPCDSBUFFERDESC dbsd
825 ) {
826         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
827         WARN("(%p) already initialized\n", This);
828         return DSERR_ALREADYINITIALIZED;
829 }
830
831 static HRESULT WINAPI IDirectSoundBufferImpl_GetCaps(
832         LPDIRECTSOUNDBUFFER8 iface,LPDSBCAPS caps
833 ) {
834         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
835         TRACE("(%p)->(%p)\n",This,caps);
836
837         if (caps == NULL) {
838                 WARN("invalid parameter: caps == NULL\n");
839                 return DSERR_INVALIDPARAM;
840         }
841
842         if (caps->dwSize < sizeof(*caps)) {
843                 WARN("invalid parameter: caps->dwSize = %d\n",caps->dwSize);
844                 return DSERR_INVALIDPARAM;
845         }
846
847         caps->dwFlags = This->dsbd.dwFlags;
848         if (This->hwbuf) caps->dwFlags |= DSBCAPS_LOCHARDWARE;
849         else caps->dwFlags |= DSBCAPS_LOCSOFTWARE;
850
851         caps->dwBufferBytes = This->buflen;
852
853         /* According to windows, this is zero*/
854         caps->dwUnlockTransferRate = 0;
855         caps->dwPlayCpuOverhead = 0;
856
857         return DS_OK;
858 }
859
860 static HRESULT WINAPI IDirectSoundBufferImpl_QueryInterface(
861         LPDIRECTSOUNDBUFFER8 iface,REFIID riid,LPVOID *ppobj
862 ) {
863         IDirectSoundBufferImpl *This = (IDirectSoundBufferImpl *)iface;
864
865         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
866
867         if (ppobj == NULL) {
868                 WARN("invalid parameter\n");
869                 return E_INVALIDARG;
870         }
871
872         *ppobj = NULL;  /* assume failure */
873
874         if ( IsEqualGUID(riid, &IID_IUnknown) ||
875              IsEqualGUID(riid, &IID_IDirectSoundBuffer) ||
876              IsEqualGUID(riid, &IID_IDirectSoundBuffer8) ) {
877                 if (!This->secondary)
878                         SecondaryBufferImpl_Create(This, &(This->secondary));
879                 if (This->secondary) {
880                         IDirectSoundBuffer8_AddRef((LPDIRECTSOUNDBUFFER8)This->secondary);
881                         *ppobj = This->secondary;
882                         return S_OK;
883                 }
884                 WARN("IID_IDirectSoundBuffer\n");
885                 return E_NOINTERFACE;
886         }
887
888         if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
889                 if (!This->notify)
890                         IDirectSoundNotifyImpl_Create(This, &(This->notify));
891                 if (This->notify) {
892                         IDirectSoundNotify_AddRef((LPDIRECTSOUNDNOTIFY)This->notify);
893                         *ppobj = This->notify;
894                         return S_OK;
895                 }
896                 WARN("IID_IDirectSoundNotify\n");
897                 return E_NOINTERFACE;
898         }
899
900         if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
901                 if (!This->ds3db)
902                         IDirectSound3DBufferImpl_Create(This, &(This->ds3db));
903                 if (This->ds3db) {
904                         IDirectSound3DBuffer_AddRef((LPDIRECTSOUND3DBUFFER)This->ds3db);
905                         *ppobj = This->ds3db;
906                         return S_OK;
907                 }
908                 WARN("IID_IDirectSound3DBuffer\n");
909                 return E_NOINTERFACE;
910         }
911
912         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
913                 ERR("app requested IDirectSound3DListener on secondary buffer\n");
914                 return E_NOINTERFACE;
915         }
916
917         if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
918                 if (!This->iks)
919                         IKsBufferPropertySetImpl_Create(This, &(This->iks));
920                 if (This->iks) {
921                         IKsPropertySet_AddRef((LPKSPROPERTYSET)This->iks);
922                         *ppobj = This->iks;
923                         return S_OK;
924                 }
925                 WARN("IID_IKsPropertySet\n");
926                 return E_NOINTERFACE;
927         }
928
929         FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
930
931         return E_NOINTERFACE;
932 }
933
934 static const IDirectSoundBuffer8Vtbl dsbvt =
935 {
936         IDirectSoundBufferImpl_QueryInterface,
937         IDirectSoundBufferImpl_AddRef,
938         IDirectSoundBufferImpl_Release,
939         IDirectSoundBufferImpl_GetCaps,
940         IDirectSoundBufferImpl_GetCurrentPosition,
941         IDirectSoundBufferImpl_GetFormat,
942         IDirectSoundBufferImpl_GetVolume,
943         IDirectSoundBufferImpl_GetPan,
944         IDirectSoundBufferImpl_GetFrequency,
945         IDirectSoundBufferImpl_GetStatus,
946         IDirectSoundBufferImpl_Initialize,
947         IDirectSoundBufferImpl_Lock,
948         IDirectSoundBufferImpl_Play,
949         IDirectSoundBufferImpl_SetCurrentPosition,
950         IDirectSoundBufferImpl_SetFormat,
951         IDirectSoundBufferImpl_SetVolume,
952         IDirectSoundBufferImpl_SetPan,
953         IDirectSoundBufferImpl_SetFrequency,
954         IDirectSoundBufferImpl_Stop,
955         IDirectSoundBufferImpl_Unlock,
956         IDirectSoundBufferImpl_Restore,
957         IDirectSoundBufferImpl_SetFX,
958         IDirectSoundBufferImpl_AcquireResources,
959         IDirectSoundBufferImpl_GetObjectInPath
960 };
961
962 HRESULT IDirectSoundBufferImpl_Create(
963         DirectSoundDevice * device,
964         IDirectSoundBufferImpl **pdsb,
965         LPCDSBUFFERDESC dsbd)
966 {
967         IDirectSoundBufferImpl *dsb;
968         LPWAVEFORMATEX wfex = dsbd->lpwfxFormat;
969         HRESULT err = DS_OK;
970         DWORD capf = 0;
971         int use_hw, alloc_size, cp_size;
972         TRACE("(%p,%p,%p)\n",device,pdsb,dsbd);
973
974         if (dsbd->dwBufferBytes < DSBSIZE_MIN || dsbd->dwBufferBytes > DSBSIZE_MAX) {
975                 WARN("invalid parameter: dsbd->dwBufferBytes = %d\n", dsbd->dwBufferBytes);
976                 *pdsb = NULL;
977                 return DSERR_INVALIDPARAM; /* FIXME: which error? */
978         }
979
980         dsb = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*dsb));
981
982         if (dsb == 0) {
983                 WARN("out of memory\n");
984                 *pdsb = NULL;
985                 return DSERR_OUTOFMEMORY;
986         }
987
988         TRACE("Created buffer at %p\n", dsb);
989
990         dsb->ref = 0;
991         dsb->secondary = 0;
992         dsb->device = device;
993         dsb->lpVtbl = &dsbvt;
994         dsb->iks = NULL;
995
996         /* size depends on version */
997         CopyMemory(&dsb->dsbd, dsbd, dsbd->dwSize);
998
999         /* variable sized struct so calculate size based on format */
1000         if (wfex->wFormatTag == WAVE_FORMAT_PCM) {
1001                 alloc_size = sizeof(WAVEFORMATEX);
1002                 cp_size = sizeof(PCMWAVEFORMAT);
1003         } else 
1004                 alloc_size = cp_size = sizeof(WAVEFORMATEX) + wfex->cbSize;
1005
1006         dsb->pwfx = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,alloc_size);
1007         if (dsb->pwfx == NULL) {
1008                 WARN("out of memory\n");
1009                 HeapFree(GetProcessHeap(),0,dsb);
1010                 *pdsb = NULL;
1011                 return DSERR_OUTOFMEMORY;
1012         }
1013
1014         CopyMemory(dsb->pwfx, wfex, cp_size);
1015
1016         if (dsbd->dwBufferBytes % dsbd->lpwfxFormat->nBlockAlign)
1017                 dsb->buflen = dsbd->dwBufferBytes + 
1018                         (dsbd->lpwfxFormat->nBlockAlign - 
1019                         (dsbd->dwBufferBytes % dsbd->lpwfxFormat->nBlockAlign));
1020         else
1021                 dsb->buflen = dsbd->dwBufferBytes;
1022
1023         dsb->freq = dsbd->lpwfxFormat->nSamplesPerSec;
1024         dsb->notify = NULL;
1025         dsb->notifies = NULL;
1026         dsb->nrofnotifies = 0;
1027         dsb->hwnotify = 0;
1028
1029         /* Check necessary hardware mixing capabilities */
1030         if (wfex->nChannels==2) capf |= DSCAPS_SECONDARYSTEREO;
1031         else capf |= DSCAPS_SECONDARYMONO;
1032         if (wfex->wBitsPerSample==16) capf |= DSCAPS_SECONDARY16BIT;
1033         else capf |= DSCAPS_SECONDARY8BIT;
1034
1035         use_hw = !!(dsbd->dwFlags & DSBCAPS_LOCHARDWARE);
1036         TRACE("use_hw = %d, capf = 0x%08x, device->drvcaps.dwFlags = 0x%08x\n", use_hw, capf, device->drvcaps.dwFlags);
1037         if (use_hw && ((device->drvcaps.dwFlags & capf) != capf || !device->driver))
1038         {
1039                 if (device->driver)
1040                         WARN("Format not supported for hardware buffer\n");
1041                 HeapFree(GetProcessHeap(),0,dsb->pwfx);
1042                 HeapFree(GetProcessHeap(),0,dsb);
1043                 *pdsb = NULL;
1044                 if ((device->drvcaps.dwFlags & capf) != capf)
1045                         return DSERR_BADFORMAT;
1046                 return DSERR_GENERIC;
1047         }
1048
1049         /* FIXME: check hardware sample rate mixing capabilities */
1050         /* FIXME: check app hints for software/hardware buffer (STATIC, LOCHARDWARE, etc) */
1051         /* FIXME: check whether any hardware buffers are left */
1052         /* FIXME: handle DSDHEAP_CREATEHEAP for hardware buffers */
1053
1054         /* Allocate an empty buffer */
1055         dsb->buffer = HeapAlloc(GetProcessHeap(),0,sizeof(*(dsb->buffer)));
1056         if (dsb->buffer == NULL) {
1057                 WARN("out of memory\n");
1058                 HeapFree(GetProcessHeap(),0,dsb->pwfx);
1059                 HeapFree(GetProcessHeap(),0,dsb);
1060                 *pdsb = NULL;
1061                 return DSERR_OUTOFMEMORY;
1062         }
1063
1064         /* Allocate system memory for buffer if applicable */
1065         if ((device->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY) || !use_hw) {
1066                 dsb->buffer->memory = HeapAlloc(GetProcessHeap(),0,dsb->buflen);
1067                 if (dsb->buffer->memory == NULL) {
1068                         WARN("out of memory\n");
1069                         HeapFree(GetProcessHeap(),0,dsb->pwfx);
1070                         HeapFree(GetProcessHeap(),0,dsb->buffer);
1071                         HeapFree(GetProcessHeap(),0,dsb);
1072                         *pdsb = NULL;
1073                         return DSERR_OUTOFMEMORY;
1074                 }
1075         }
1076
1077         /* Allocate the hardware buffer */
1078         if (use_hw) {
1079                 err = IDsDriver_CreateSoundBuffer(device->driver,wfex,dsbd->dwFlags,0,
1080                                                   &(dsb->buflen),&(dsb->buffer->memory),
1081                                                   (LPVOID*)&(dsb->hwbuf));
1082                 if (FAILED(err))
1083                 {
1084                         WARN("Failed to create hardware secondary buffer: %08x\n", err);
1085                         if (device->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY)
1086                                 HeapFree(GetProcessHeap(),0,dsb->buffer->memory);
1087                         HeapFree(GetProcessHeap(),0,dsb->buffer);
1088                         HeapFree(GetProcessHeap(),0,dsb->pwfx);
1089                         HeapFree(GetProcessHeap(),0,dsb);
1090                         *pdsb = NULL;
1091                         return DSERR_GENERIC;
1092                 }
1093         }
1094
1095         dsb->buffer->ref = 1;
1096         list_init(&dsb->buffer->buffers);
1097         list_add_head(&dsb->buffer->buffers, &dsb->entry);
1098         FillMemory(dsb->buffer->memory, dsb->buflen, dsbd->lpwfxFormat->wBitsPerSample == 8 ? 128 : 0);
1099
1100         /* It's not necessary to initialize values to zero since */
1101         /* we allocated this structure with HEAP_ZERO_MEMORY... */
1102         dsb->buf_mixpos = dsb->sec_mixpos = 0;
1103         dsb->state = STATE_STOPPED;
1104
1105         dsb->freqAdjust = ((DWORD64)dsb->freq << DSOUND_FREQSHIFT) / device->pwfx->nSamplesPerSec;
1106         dsb->nAvgBytesPerSec = dsb->freq *
1107                 dsbd->lpwfxFormat->nBlockAlign;
1108
1109         /* calculate fragment size and write lead */
1110         DSOUND_RecalcFormat(dsb);
1111
1112         if (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D) {
1113                 dsb->ds3db_ds3db.dwSize = sizeof(DS3DBUFFER);
1114                 dsb->ds3db_ds3db.vPosition.x = 0.0;
1115                 dsb->ds3db_ds3db.vPosition.y = 0.0;
1116                 dsb->ds3db_ds3db.vPosition.z = 0.0;
1117                 dsb->ds3db_ds3db.vVelocity.x = 0.0;
1118                 dsb->ds3db_ds3db.vVelocity.y = 0.0;
1119                 dsb->ds3db_ds3db.vVelocity.z = 0.0;
1120                 dsb->ds3db_ds3db.dwInsideConeAngle = DS3D_DEFAULTCONEANGLE;
1121                 dsb->ds3db_ds3db.dwOutsideConeAngle = DS3D_DEFAULTCONEANGLE;
1122                 dsb->ds3db_ds3db.vConeOrientation.x = 0.0;
1123                 dsb->ds3db_ds3db.vConeOrientation.y = 0.0;
1124                 dsb->ds3db_ds3db.vConeOrientation.z = 0.0;
1125                 dsb->ds3db_ds3db.lConeOutsideVolume = DS3D_DEFAULTCONEOUTSIDEVOLUME;
1126                 dsb->ds3db_ds3db.flMinDistance = DS3D_DEFAULTMINDISTANCE;
1127                 dsb->ds3db_ds3db.flMaxDistance = DS3D_DEFAULTMAXDISTANCE;
1128                 dsb->ds3db_ds3db.dwMode = DS3DMODE_NORMAL;
1129
1130                 dsb->ds3db_need_recalc = FALSE;
1131                 DSOUND_Calc3DBuffer(dsb);
1132         } else
1133                 DSOUND_RecalcVolPan(&(dsb->volpan));
1134
1135         RtlInitializeResource(&dsb->lock);
1136
1137         /* register buffer if not primary */
1138         if (!(dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER)) {
1139                 err = DirectSoundDevice_AddBuffer(device, dsb);
1140                 if (err != DS_OK) {
1141                         HeapFree(GetProcessHeap(),0,dsb->buffer->memory);
1142                         HeapFree(GetProcessHeap(),0,dsb->buffer);
1143                         RtlDeleteResource(&dsb->lock);
1144                         HeapFree(GetProcessHeap(),0,dsb->pwfx);
1145                         HeapFree(GetProcessHeap(),0,dsb);
1146                         dsb = NULL;
1147                 }
1148         }
1149
1150         *pdsb = dsb;
1151         return err;
1152 }
1153
1154 HRESULT IDirectSoundBufferImpl_Destroy(
1155     IDirectSoundBufferImpl *pdsb)
1156 {
1157     TRACE("(%p)\n",pdsb);
1158
1159     /* This keeps the *_Destroy functions from possibly deleting
1160      * this object until it is ready to be deleted */
1161     IDirectSoundBufferImpl_AddRef((LPDIRECTSOUNDBUFFER8)pdsb);
1162
1163     if (pdsb->iks) {
1164         WARN("iks not NULL\n");
1165         IKsBufferPropertySetImpl_Destroy(pdsb->iks);
1166         pdsb->iks = NULL;
1167     }
1168
1169     if (pdsb->ds3db) {
1170         WARN("ds3db not NULL\n");
1171         IDirectSound3DBufferImpl_Destroy(pdsb->ds3db);
1172         pdsb->ds3db = NULL;
1173     }
1174
1175     if (pdsb->notify) {
1176         WARN("notify not NULL\n");
1177         IDirectSoundNotifyImpl_Destroy(pdsb->notify);
1178         pdsb->notify = NULL;
1179     }
1180
1181     if (pdsb->secondary) {
1182         WARN("dsb not NULL\n");
1183         SecondaryBufferImpl_Destroy(pdsb->secondary);
1184         pdsb->secondary = NULL;
1185     }
1186
1187     while (IDirectSoundBuffer8_Release((LPDIRECTSOUNDBUFFER8)pdsb) > 0);
1188
1189     return S_OK;
1190 }
1191
1192 HRESULT IDirectSoundBufferImpl_Duplicate(
1193     DirectSoundDevice *device,
1194     IDirectSoundBufferImpl **ppdsb,
1195     IDirectSoundBufferImpl *pdsb)
1196 {
1197     IDirectSoundBufferImpl *dsb;
1198     HRESULT hres = DS_OK;
1199     int size;
1200     TRACE("(%p,%p,%p)\n", device, pdsb, pdsb);
1201
1202     dsb = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*dsb));
1203
1204     if (dsb == NULL) {
1205         WARN("out of memory\n");
1206         *ppdsb = NULL;
1207         return DSERR_OUTOFMEMORY;
1208     }
1209
1210     CopyMemory(dsb, pdsb, sizeof(IDirectSoundBufferImpl));
1211
1212     if (pdsb->hwbuf) {
1213         TRACE("duplicating hardware buffer\n");
1214
1215         hres = IDsDriver_DuplicateSoundBuffer(device->driver, pdsb->hwbuf,
1216                                               (LPVOID *)&dsb->hwbuf);
1217         if (FAILED(hres)) {
1218             WARN("IDsDriver_DuplicateSoundBuffer failed (%08x)\n", hres);
1219             HeapFree(GetProcessHeap(),0,dsb);
1220             *ppdsb = NULL;
1221             return hres;
1222         }
1223     }
1224
1225     dsb->buffer->ref++;
1226     list_add_head(&dsb->buffer->buffers, &dsb->entry);
1227     dsb->ref = 0;
1228     dsb->state = STATE_STOPPED;
1229     dsb->buf_mixpos = dsb->sec_mixpos = 0;
1230     dsb->device = device;
1231     dsb->ds3db = NULL;
1232     dsb->iks = NULL; /* FIXME? */
1233     dsb->secondary = NULL;
1234     dsb->tmp_buffer = NULL;
1235     DSOUND_RecalcFormat(dsb);
1236     DSOUND_MixToTemporary(dsb, 0, dsb->buflen, FALSE);
1237
1238     /* variable sized struct so calculate size based on format */
1239     size = sizeof(WAVEFORMATEX) + pdsb->pwfx->cbSize;
1240
1241     dsb->pwfx = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,size);
1242     if (dsb->pwfx == NULL) {
1243             WARN("out of memory\n");
1244             HeapFree(GetProcessHeap(),0,dsb->buffer);
1245             HeapFree(GetProcessHeap(),0,dsb);
1246             *ppdsb = NULL;
1247             return DSERR_OUTOFMEMORY;
1248     }
1249
1250     CopyMemory(dsb->pwfx, pdsb->pwfx, size);
1251
1252     RtlInitializeResource(&dsb->lock);
1253
1254     /* register buffer */
1255     hres = DirectSoundDevice_AddBuffer(device, dsb);
1256     if (hres != DS_OK) {
1257         RtlDeleteResource(&dsb->lock);
1258         HeapFree(GetProcessHeap(),0,dsb->tmp_buffer);
1259         HeapFree(GetProcessHeap(),0,dsb->buffer);
1260         HeapFree(GetProcessHeap(),0,dsb->pwfx);
1261         HeapFree(GetProcessHeap(),0,dsb);
1262         *ppdsb = 0;
1263     }
1264
1265     *ppdsb = dsb;
1266     return hres;
1267 }
1268
1269 /*******************************************************************************
1270  *              SecondaryBuffer
1271  */
1272
1273 static HRESULT WINAPI SecondaryBufferImpl_QueryInterface(
1274         LPDIRECTSOUNDBUFFER8 iface,REFIID riid,LPVOID *ppobj)
1275 {
1276         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1277         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
1278
1279         return IDirectSoundBufferImpl_QueryInterface((LPDIRECTSOUNDBUFFER8)This->dsb,riid,ppobj);
1280 }
1281
1282 static ULONG WINAPI SecondaryBufferImpl_AddRef(LPDIRECTSOUNDBUFFER8 iface)
1283 {
1284     SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1285     ULONG ref = InterlockedIncrement(&(This->ref));
1286     TRACE("(%p) ref was %d\n", This, ref - 1);
1287     return ref;
1288 }
1289
1290 static ULONG WINAPI SecondaryBufferImpl_Release(LPDIRECTSOUNDBUFFER8 iface)
1291 {
1292     SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1293     ULONG ref;
1294     TRACE("(%p)\n", This);
1295     ref = InterlockedDecrement(&(This->ref));
1296     TRACE("ref was %d\n", ref + 1);
1297
1298     if (!ref) {
1299         This->dsb->secondary = NULL;
1300         IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER8)This->dsb);
1301         HeapFree(GetProcessHeap(), 0, This);
1302         TRACE("(%p) released\n", This);
1303     }
1304     return ref;
1305 }
1306
1307 static HRESULT WINAPI SecondaryBufferImpl_GetCaps(
1308         LPDIRECTSOUNDBUFFER8 iface,LPDSBCAPS caps)
1309 {
1310         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1311         TRACE("(%p)->(%p)\n",This,caps);
1312
1313         return IDirectSoundBufferImpl_GetCaps((LPDIRECTSOUNDBUFFER8)This->dsb,caps);
1314 }
1315
1316 static HRESULT WINAPI SecondaryBufferImpl_GetCurrentPosition(
1317         LPDIRECTSOUNDBUFFER8 iface,LPDWORD playpos,LPDWORD writepos)
1318 {
1319         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1320         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
1321
1322         return IDirectSoundBufferImpl_GetCurrentPosition((LPDIRECTSOUNDBUFFER8)This->dsb,playpos,writepos);
1323 }
1324
1325 static HRESULT WINAPI SecondaryBufferImpl_GetFormat(
1326         LPDIRECTSOUNDBUFFER8 iface,LPWAVEFORMATEX lpwf,DWORD wfsize,LPDWORD wfwritten)
1327 {
1328         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1329         TRACE("(%p,%p,%d,%p)\n",This,lpwf,wfsize,wfwritten);
1330
1331         return IDirectSoundBufferImpl_GetFormat((LPDIRECTSOUNDBUFFER8)This->dsb,lpwf,wfsize,wfwritten);
1332 }
1333
1334 static HRESULT WINAPI SecondaryBufferImpl_GetVolume(
1335         LPDIRECTSOUNDBUFFER8 iface,LPLONG vol)
1336 {
1337         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1338         TRACE("(%p,%p)\n",This,vol);
1339
1340         return IDirectSoundBufferImpl_GetVolume((LPDIRECTSOUNDBUFFER8)This->dsb,vol);
1341 }
1342
1343 static HRESULT WINAPI SecondaryBufferImpl_GetPan(
1344         LPDIRECTSOUNDBUFFER8 iface,LPLONG pan)
1345 {
1346         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1347         TRACE("(%p,%p)\n",This,pan);
1348
1349         return IDirectSoundBufferImpl_GetPan((LPDIRECTSOUNDBUFFER8)This->dsb,pan);
1350 }
1351
1352 static HRESULT WINAPI SecondaryBufferImpl_GetFrequency(
1353         LPDIRECTSOUNDBUFFER8 iface,LPDWORD freq)
1354 {
1355         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1356         TRACE("(%p,%p)\n",This,freq);
1357
1358         return IDirectSoundBufferImpl_GetFrequency((LPDIRECTSOUNDBUFFER8)This->dsb,freq);
1359 }
1360
1361 static HRESULT WINAPI SecondaryBufferImpl_GetStatus(
1362         LPDIRECTSOUNDBUFFER8 iface,LPDWORD status)
1363 {
1364         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1365         TRACE("(%p,%p)\n",This,status);
1366
1367         return IDirectSoundBufferImpl_GetStatus((LPDIRECTSOUNDBUFFER8)This->dsb,status);
1368 }
1369
1370 static HRESULT WINAPI SecondaryBufferImpl_Initialize(
1371         LPDIRECTSOUNDBUFFER8 iface,LPDIRECTSOUND dsound,LPCDSBUFFERDESC dbsd)
1372 {
1373         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1374         TRACE("(%p,%p,%p)\n",This,dsound,dbsd);
1375
1376         return IDirectSoundBufferImpl_Initialize((LPDIRECTSOUNDBUFFER8)This->dsb,dsound,dbsd);
1377 }
1378
1379 static HRESULT WINAPI SecondaryBufferImpl_Lock(
1380     LPDIRECTSOUNDBUFFER8 iface,
1381     DWORD writecursor,
1382     DWORD writebytes,
1383     LPVOID *lplpaudioptr1,
1384     LPDWORD audiobytes1,
1385     LPVOID *lplpaudioptr2,
1386     LPDWORD audiobytes2,
1387     DWORD dwFlags)
1388 {
1389     SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1390     TRACE("(%p,%d,%d,%p,%p,%p,%p,0x%08x)\n",
1391         This,writecursor,writebytes,lplpaudioptr1,audiobytes1,lplpaudioptr2,audiobytes2,dwFlags);
1392
1393     return IDirectSoundBufferImpl_Lock((LPDIRECTSOUNDBUFFER8)This->dsb,
1394         writecursor,writebytes,lplpaudioptr1,audiobytes1,lplpaudioptr2,audiobytes2,dwFlags);
1395 }
1396
1397 static HRESULT WINAPI SecondaryBufferImpl_Play(
1398         LPDIRECTSOUNDBUFFER8 iface,DWORD reserved1,DWORD reserved2,DWORD flags)
1399 {
1400         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1401         TRACE("(%p,%08x,%08x,%08x)\n",This,reserved1,reserved2,flags);
1402
1403         return IDirectSoundBufferImpl_Play((LPDIRECTSOUNDBUFFER8)This->dsb,reserved1,reserved2,flags);
1404 }
1405
1406 static HRESULT WINAPI SecondaryBufferImpl_SetCurrentPosition(
1407         LPDIRECTSOUNDBUFFER8 iface,DWORD newpos)
1408 {
1409         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1410         TRACE("(%p,%d)\n",This,newpos);
1411
1412         return IDirectSoundBufferImpl_SetCurrentPosition((LPDIRECTSOUNDBUFFER8)This->dsb,newpos);
1413 }
1414
1415 static HRESULT WINAPI SecondaryBufferImpl_SetFormat(
1416         LPDIRECTSOUNDBUFFER8 iface,LPCWAVEFORMATEX wfex)
1417 {
1418         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1419         TRACE("(%p,%p)\n",This,wfex);
1420
1421         return IDirectSoundBufferImpl_SetFormat((LPDIRECTSOUNDBUFFER8)This->dsb,wfex);
1422 }
1423
1424 static HRESULT WINAPI SecondaryBufferImpl_SetVolume(
1425         LPDIRECTSOUNDBUFFER8 iface,LONG vol)
1426 {
1427         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1428         TRACE("(%p,%d)\n",This,vol);
1429
1430         return IDirectSoundBufferImpl_SetVolume((LPDIRECTSOUNDBUFFER8)This->dsb,vol);
1431 }
1432
1433 static HRESULT WINAPI SecondaryBufferImpl_SetPan(
1434         LPDIRECTSOUNDBUFFER8 iface,LONG pan)
1435 {
1436         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1437         TRACE("(%p,%d)\n",This,pan);
1438
1439         return IDirectSoundBufferImpl_SetPan((LPDIRECTSOUNDBUFFER8)This->dsb,pan);
1440 }
1441
1442 static HRESULT WINAPI SecondaryBufferImpl_SetFrequency(
1443         LPDIRECTSOUNDBUFFER8 iface,DWORD freq)
1444 {
1445         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1446         TRACE("(%p,%d)\n",This,freq);
1447
1448         return IDirectSoundBufferImpl_SetFrequency((LPDIRECTSOUNDBUFFER8)This->dsb,freq);
1449 }
1450
1451 static HRESULT WINAPI SecondaryBufferImpl_Stop(LPDIRECTSOUNDBUFFER8 iface)
1452 {
1453         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1454         TRACE("(%p)\n",This);
1455
1456         return IDirectSoundBufferImpl_Stop((LPDIRECTSOUNDBUFFER8)This->dsb);
1457 }
1458
1459 static HRESULT WINAPI SecondaryBufferImpl_Unlock(
1460     LPDIRECTSOUNDBUFFER8 iface,
1461     LPVOID lpvAudioPtr1,
1462     DWORD dwAudioBytes1,
1463     LPVOID lpvAudioPtr2,
1464     DWORD dwAudioBytes2)
1465 {
1466     SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1467     TRACE("(%p,%p,%d,%p,%d)\n",
1468         This, lpvAudioPtr1, dwAudioBytes1, lpvAudioPtr2, dwAudioBytes2);
1469
1470     return IDirectSoundBufferImpl_Unlock((LPDIRECTSOUNDBUFFER8)This->dsb,
1471         lpvAudioPtr1,dwAudioBytes1,lpvAudioPtr2,dwAudioBytes2);
1472 }
1473
1474 static HRESULT WINAPI SecondaryBufferImpl_Restore(
1475         LPDIRECTSOUNDBUFFER8 iface)
1476 {
1477         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1478         TRACE("(%p)\n",This);
1479
1480         return IDirectSoundBufferImpl_Restore((LPDIRECTSOUNDBUFFER8)This->dsb);
1481 }
1482
1483 static HRESULT WINAPI SecondaryBufferImpl_SetFX(
1484         LPDIRECTSOUNDBUFFER8 iface,DWORD dwEffectsCount,LPDSEFFECTDESC pDSFXDesc,LPDWORD pdwResultCodes)
1485 {
1486         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1487         TRACE("(%p,%u,%p,%p)\n",This,dwEffectsCount,pDSFXDesc,pdwResultCodes);
1488
1489         return IDirectSoundBufferImpl_SetFX((LPDIRECTSOUNDBUFFER8)This->dsb,dwEffectsCount,pDSFXDesc,pdwResultCodes);
1490 }
1491
1492 static HRESULT WINAPI SecondaryBufferImpl_AcquireResources(
1493         LPDIRECTSOUNDBUFFER8 iface,DWORD dwFlags,DWORD dwEffectsCount,LPDWORD pdwResultCodes)
1494 {
1495         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1496         TRACE("(%p,%08u,%u,%p)\n",This,dwFlags,dwEffectsCount,pdwResultCodes);
1497
1498         return IDirectSoundBufferImpl_AcquireResources((LPDIRECTSOUNDBUFFER8)This->dsb,dwFlags,dwEffectsCount,pdwResultCodes);
1499 }
1500
1501 static HRESULT WINAPI SecondaryBufferImpl_GetObjectInPath(
1502         LPDIRECTSOUNDBUFFER8 iface,REFGUID rguidObject,DWORD dwIndex,REFGUID rguidInterface,LPVOID* ppObject)
1503 {
1504         SecondaryBufferImpl *This = (SecondaryBufferImpl *)iface;
1505         TRACE("(%p,%s,%u,%s,%p)\n",This,debugstr_guid(rguidObject),dwIndex,debugstr_guid(rguidInterface),ppObject);
1506
1507         return IDirectSoundBufferImpl_GetObjectInPath((LPDIRECTSOUNDBUFFER8)This->dsb,rguidObject,dwIndex,rguidInterface,ppObject);
1508 }
1509
1510 static const IDirectSoundBuffer8Vtbl sbvt =
1511 {
1512         SecondaryBufferImpl_QueryInterface,
1513         SecondaryBufferImpl_AddRef,
1514         SecondaryBufferImpl_Release,
1515         SecondaryBufferImpl_GetCaps,
1516         SecondaryBufferImpl_GetCurrentPosition,
1517         SecondaryBufferImpl_GetFormat,
1518         SecondaryBufferImpl_GetVolume,
1519         SecondaryBufferImpl_GetPan,
1520         SecondaryBufferImpl_GetFrequency,
1521         SecondaryBufferImpl_GetStatus,
1522         SecondaryBufferImpl_Initialize,
1523         SecondaryBufferImpl_Lock,
1524         SecondaryBufferImpl_Play,
1525         SecondaryBufferImpl_SetCurrentPosition,
1526         SecondaryBufferImpl_SetFormat,
1527         SecondaryBufferImpl_SetVolume,
1528         SecondaryBufferImpl_SetPan,
1529         SecondaryBufferImpl_SetFrequency,
1530         SecondaryBufferImpl_Stop,
1531         SecondaryBufferImpl_Unlock,
1532         SecondaryBufferImpl_Restore,
1533         SecondaryBufferImpl_SetFX,
1534         SecondaryBufferImpl_AcquireResources,
1535         SecondaryBufferImpl_GetObjectInPath
1536 };
1537
1538 HRESULT SecondaryBufferImpl_Create(
1539         IDirectSoundBufferImpl *dsb,
1540         SecondaryBufferImpl **psb)
1541 {
1542         SecondaryBufferImpl *sb;
1543         TRACE("(%p,%p)\n",dsb,psb);
1544
1545         sb = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*sb));
1546
1547         if (sb == 0) {
1548                 WARN("out of memory\n");
1549                 *psb = NULL;
1550                 return DSERR_OUTOFMEMORY;
1551         }
1552         sb->ref = 0;
1553         sb->dsb = dsb;
1554         sb->lpVtbl = &sbvt;
1555
1556         IDirectSoundBuffer8_AddRef((LPDIRECTSOUNDBUFFER8)dsb);
1557         *psb = sb;
1558         return S_OK;
1559 }
1560
1561 static HRESULT SecondaryBufferImpl_Destroy(
1562     SecondaryBufferImpl *pdsb)
1563 {
1564     TRACE("(%p)\n",pdsb);
1565
1566     while (SecondaryBufferImpl_Release((LPDIRECTSOUNDBUFFER8)pdsb) > 0);
1567
1568     return S_OK;
1569 }