Implement A->W call for GetNamedSecurityInfo.
[wine] / dlls / dsound / buffer.c
1 /*                      DirectSound
2  *
3  * Copyright 1998 Marcus Meissner
4  * Copyright 1998 Rob Riggs
5  * Copyright 2000-2002 TransGaming Technologies, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include <assert.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <sys/fcntl.h>
28 #ifdef HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif
31 #include <stdlib.h>
32 #include <string.h>
33 #include <math.h>
34
35 #define NONAMELESSSTRUCT
36 #define NONAMELESSUNION
37 #include "windef.h"
38 #include "winbase.h"
39 #include "wingdi.h"
40 #include "winuser.h"
41 #include "winerror.h"
42 #include "mmsystem.h"
43 #include "winreg.h"
44 #include "winternl.h"
45 #include "mmddk.h"
46 #include "wine/windef16.h"
47 #include "wine/debug.h"
48 #include "dsound.h"
49 #include "dsdriver.h"
50 #include "dsound_private.h"
51
52 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
53
54 /*******************************************************************************
55  *              IDirectSoundNotify
56  */
57 static HRESULT WINAPI IDirectSoundNotifyImpl_QueryInterface(
58         LPDIRECTSOUNDNOTIFY iface,REFIID riid,LPVOID *ppobj
59 ) {
60         ICOM_THIS(IDirectSoundNotifyImpl,iface);
61         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
62
63         if (This->dsb == NULL) {
64                 WARN("invalid parameter\n");
65                 return E_INVALIDARG;
66         }
67
68         return IDirectSoundBuffer_QueryInterface((LPDIRECTSOUNDBUFFER)This->dsb, riid, ppobj);
69 }
70
71 static ULONG WINAPI IDirectSoundNotifyImpl_AddRef(LPDIRECTSOUNDNOTIFY iface) {
72         ICOM_THIS(IDirectSoundNotifyImpl,iface);
73         DWORD ref;
74
75         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
76
77         ref = InterlockedIncrement(&(This->ref));
78         return ref;
79 }
80
81 static ULONG WINAPI IDirectSoundNotifyImpl_Release(LPDIRECTSOUNDNOTIFY iface) {
82         ICOM_THIS(IDirectSoundNotifyImpl,iface);
83         DWORD ref;
84
85         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
86
87         ref = InterlockedDecrement(&(This->ref));
88         if (ref == 0) {
89                 IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER)This->dsb);
90                 This->dsb->notify = NULL;
91                 HeapFree(GetProcessHeap(),0,This);
92                 TRACE("(%p) released\n",This);
93         }
94         return ref;
95 }
96
97 static HRESULT WINAPI IDirectSoundNotifyImpl_SetNotificationPositions(
98         LPDIRECTSOUNDNOTIFY iface,DWORD howmuch,LPCDSBPOSITIONNOTIFY notify
99 ) {
100         ICOM_THIS(IDirectSoundNotifyImpl,iface);
101         TRACE("(%p,0x%08lx,%p)\n",This,howmuch,notify);
102
103         if (howmuch > 0 && notify == NULL) {
104             WARN("invalid parameter: notify == NULL\n");
105             return DSERR_INVALIDPARAM;
106         }
107
108         if (TRACE_ON(dsound)) {
109             int i;
110             for (i=0;i<howmuch;i++)
111                 TRACE("notify at %ld to 0x%08lx\n",
112                     notify[i].dwOffset,(DWORD)notify[i].hEventNotify);
113         }
114
115         if (This->dsb->hwnotify) {
116             HRESULT hres;
117             hres = IDsDriverNotify_SetNotificationPositions(This->dsb->hwnotify, howmuch, notify);
118             if (hres != DS_OK)
119                     WARN("IDsDriverNotify_SetNotificationPositions failed\n");
120             return hres;
121         } else if (howmuch > 0) {
122             /* Make an internal copy of the caller-supplied array.
123              * Replace the existing copy if one is already present. */
124             if (This->dsb->notifies)
125                     This->dsb->notifies = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
126                         This->dsb->notifies, howmuch * sizeof(DSBPOSITIONNOTIFY));
127             else
128                     This->dsb->notifies = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
129                         howmuch * sizeof(DSBPOSITIONNOTIFY));
130
131             if (This->dsb->notifies == NULL) {
132                     WARN("out of memory\n");
133                     return DSERR_OUTOFMEMORY;
134             }
135             memcpy(This->dsb->notifies, notify, howmuch * sizeof(DSBPOSITIONNOTIFY));
136             This->dsb->nrofnotifies = howmuch;
137         } else {
138            if (This->dsb->notifies) {
139                HeapFree(GetProcessHeap(), 0, This->dsb->notifies);
140                This->dsb->notifies = NULL;
141            }
142            This->dsb->nrofnotifies = 0;
143         }
144
145         return S_OK;
146 }
147
148 ICOM_VTABLE(IDirectSoundNotify) dsnvt =
149 {
150     ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
151     IDirectSoundNotifyImpl_QueryInterface,
152     IDirectSoundNotifyImpl_AddRef,
153     IDirectSoundNotifyImpl_Release,
154     IDirectSoundNotifyImpl_SetNotificationPositions,
155 };
156
157 HRESULT WINAPI IDirectSoundNotifyImpl_Create(
158     IDirectSoundBufferImpl * dsb,
159     IDirectSoundNotifyImpl **pdsn)
160 {
161     IDirectSoundNotifyImpl * dsn;
162     TRACE("(%p,%p)\n",dsb,pdsn);
163
164     dsn = (IDirectSoundNotifyImpl*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(dsn));
165
166     if (dsn == NULL) {
167         WARN("out of memory\n");
168         return DSERR_OUTOFMEMORY;
169     }
170
171     dsn->ref = 0;
172     dsn->lpVtbl = &dsnvt;
173     dsn->dsb = dsb;
174     dsb->notify = dsn;
175     IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)dsb);
176
177     *pdsn = dsn;
178     return DS_OK;
179 }
180
181 HRESULT WINAPI IDirectSoundNotifyImpl_Destroy(
182     IDirectSoundNotifyImpl *pdsn)
183 {
184     TRACE("(%p)\n",pdsn);
185
186     while (IDirectSoundNotifyImpl_Release((LPDIRECTSOUNDNOTIFY)pdsn) > 0);
187
188     return DS_OK;
189 }
190
191 /*******************************************************************************
192  *              IDirectSoundBuffer
193  */
194
195 static HRESULT WINAPI IDirectSoundBufferImpl_SetFormat(
196         LPDIRECTSOUNDBUFFER8 iface,LPCWAVEFORMATEX wfex
197 ) {
198         ICOM_THIS(IDirectSoundBufferImpl,iface);
199
200         TRACE("(%p,%p)\n",This,wfex);
201         /* This method is not available on secondary buffers */
202         WARN("invalid call\n");
203         return DSERR_INVALIDCALL;
204 }
205
206 static HRESULT WINAPI IDirectSoundBufferImpl_SetVolume(
207         LPDIRECTSOUNDBUFFER8 iface,LONG vol
208 ) {
209         ICOM_THIS(IDirectSoundBufferImpl,iface);
210         LONG oldVol;
211
212         TRACE("(%p,%ld)\n",This,vol);
213
214         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
215                 WARN("control unavailable: This->dsbd.dwFlags = 0x%08lx\n", This->dsbd.dwFlags);
216                 return DSERR_CONTROLUNAVAIL;
217         }
218
219         if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN)) {
220                 WARN("invalid parameter: vol = %ld\n", vol);
221                 return DSERR_INVALIDPARAM;
222         }
223
224         /* **** */
225         EnterCriticalSection(&(This->lock));
226
227         if (This->dsbd.dwFlags & DSBCAPS_CTRL3D) {
228                 oldVol = This->ds3db_lVolume;
229                 This->ds3db_lVolume = vol;
230         } else {
231                 oldVol = This->volpan.lVolume;
232                 This->volpan.lVolume = vol;
233                 if (vol != oldVol)
234                         DSOUND_RecalcVolPan(&(This->volpan));
235         }
236
237         if (vol != oldVol) {
238                 if (This->hwbuf) {
239                         HRESULT hres;
240                         hres = IDsDriverBuffer_SetVolumePan(This->hwbuf, &(This->volpan));
241                         if (hres != DS_OK)
242                                 WARN("IDsDriverBuffer_SetVolumePan failed\n");
243                 } else
244                         DSOUND_ForceRemix(This);
245         }
246
247         LeaveCriticalSection(&(This->lock));
248         /* **** */
249
250         return DS_OK;
251 }
252
253 static HRESULT WINAPI IDirectSoundBufferImpl_GetVolume(
254         LPDIRECTSOUNDBUFFER8 iface,LPLONG vol
255 ) {
256         ICOM_THIS(IDirectSoundBufferImpl,iface);
257         TRACE("(%p,%p)\n",This,vol);
258
259         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
260                 WARN("control unavailable\n");
261                 return DSERR_CONTROLUNAVAIL;
262         }
263
264         if (vol == NULL) {
265                 WARN("invalid parameter: vol == NULL\n");
266                 return DSERR_INVALIDPARAM;
267         }
268
269         *vol = This->volpan.lVolume;
270
271         return DS_OK;
272 }
273
274 static HRESULT WINAPI IDirectSoundBufferImpl_SetFrequency(
275         LPDIRECTSOUNDBUFFER8 iface,DWORD freq
276 ) {
277         ICOM_THIS(IDirectSoundBufferImpl,iface);
278         DWORD oldFreq;
279
280         TRACE("(%p,%ld)\n",This,freq);
281
282         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) {
283                 WARN("control unavailable\n");
284                 return DSERR_CONTROLUNAVAIL;
285         }
286
287         if (freq == DSBFREQUENCY_ORIGINAL)
288                 freq = This->wfx.nSamplesPerSec;
289
290         if ((freq < DSBFREQUENCY_MIN) || (freq > DSBFREQUENCY_MAX)) {
291                 WARN("invalid parameter: freq = %ld\n", freq);
292                 return DSERR_INVALIDPARAM;
293         }
294
295         /* **** */
296         EnterCriticalSection(&(This->lock));
297
298         oldFreq = This->freq;
299         This->freq = freq;
300         if (freq != oldFreq) {
301                 This->freqAdjust = (freq << DSOUND_FREQSHIFT) / This->dsound->wfx.nSamplesPerSec;
302                 This->nAvgBytesPerSec = freq * This->wfx.nBlockAlign;
303                 DSOUND_RecalcFormat(This);
304                 if (!This->hwbuf)
305                         DSOUND_ForceRemix(This);
306         }
307
308         LeaveCriticalSection(&(This->lock));
309         /* **** */
310
311         return DS_OK;
312 }
313
314 static HRESULT WINAPI IDirectSoundBufferImpl_Play(
315         LPDIRECTSOUNDBUFFER8 iface,DWORD reserved1,DWORD reserved2,DWORD flags
316 ) {
317         HRESULT hres = DS_OK;
318         ICOM_THIS(IDirectSoundBufferImpl,iface);
319         TRACE("(%p,%08lx,%08lx,%08lx)\n",This,reserved1,reserved2,flags);
320
321         /* **** */
322         EnterCriticalSection(&(This->lock));
323
324         This->playflags = flags;
325         if (This->state == STATE_STOPPED) {
326                 This->leadin = TRUE;
327                 This->startpos = This->buf_mixpos;
328                 This->state = STATE_STARTING;
329         } else if (This->state == STATE_STOPPING)
330                 This->state = STATE_PLAYING;
331         if (This->hwbuf) {
332                 hres = IDsDriverBuffer_Play(This->hwbuf, 0, 0, This->playflags);
333                 if (hres != DS_OK)
334                         WARN("IDsDriverBuffer_Play failed\n");
335                 else
336                         This->state = STATE_PLAYING;
337         }
338
339         LeaveCriticalSection(&(This->lock));
340         /* **** */
341
342         return hres;
343 }
344
345 static HRESULT WINAPI IDirectSoundBufferImpl_Stop(LPDIRECTSOUNDBUFFER8 iface)
346 {
347         HRESULT hres = DS_OK;
348         ICOM_THIS(IDirectSoundBufferImpl,iface);
349         TRACE("(%p)\n",This);
350
351         /* **** */
352         EnterCriticalSection(&(This->lock));
353
354         if (This->state == STATE_PLAYING)
355                 This->state = STATE_STOPPING;
356         else if (This->state == STATE_STARTING)
357                 This->state = STATE_STOPPED;
358         if (This->hwbuf) {
359                 hres = IDsDriverBuffer_Stop(This->hwbuf);
360                 if (hres != DS_OK)
361                         WARN("IDsDriverBuffer_Stop failed\n");
362                 else
363                         This->state = STATE_STOPPED;
364         }
365         DSOUND_CheckEvent(This, 0);
366
367         LeaveCriticalSection(&(This->lock));
368         /* **** */
369
370         return hres;
371 }
372
373 static DWORD WINAPI IDirectSoundBufferImpl_AddRef(LPDIRECTSOUNDBUFFER8 iface) {
374         ICOM_THIS(IDirectSoundBufferImpl,iface);
375         DWORD ref;
376
377         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
378
379         ref = InterlockedIncrement(&(This->ref));
380         if (!ref) {
381                 FIXME("thread-safety alert! AddRef-ing with a zero refcount!\n");
382         }
383         return ref;
384 }
385
386 static DWORD WINAPI IDirectSoundBufferImpl_Release(LPDIRECTSOUNDBUFFER8 iface) {
387         ICOM_THIS(IDirectSoundBufferImpl,iface);
388         int     i;
389         DWORD ref;
390
391         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
392
393         ref = InterlockedDecrement(&(This->ref));
394         if (ref) return ref;
395
396         RtlAcquireResourceExclusive(&(This->dsound->lock), TRUE);
397         for (i=0;i<This->dsound->nrofbuffers;i++)
398                 if (This->dsound->buffers[i] == This)
399                         break;
400         if (i < This->dsound->nrofbuffers) {
401                 /* Put the last buffer of the list in the (now empty) position */
402                 This->dsound->buffers[i] = This->dsound->buffers[This->dsound->nrofbuffers - 1];
403                 This->dsound->nrofbuffers--;
404                 This->dsound->buffers = HeapReAlloc(GetProcessHeap(),0,This->dsound->buffers,sizeof(LPDIRECTSOUNDBUFFER8)*This->dsound->nrofbuffers);
405                 TRACE("(%p) buffer count is now %d\n", This, This->dsound->nrofbuffers);
406         }
407         RtlReleaseResource(&(This->dsound->lock));
408
409         DeleteCriticalSection(&(This->lock));
410
411         if (This->hwbuf) {
412                 IDsDriverBuffer_Release(This->hwbuf);
413                 if (This->dsound->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY) {
414                         This->buffer->ref--;
415                         if (This->buffer->ref==0) {
416                                 HeapFree(GetProcessHeap(),0,This->buffer->memory);
417                                 HeapFree(GetProcessHeap(),0,This->buffer);
418                         }
419                 }
420         } else {
421                 This->buffer->ref--;
422                 if (This->buffer->ref==0) {
423                         HeapFree(GetProcessHeap(),0,This->buffer->memory);
424                         HeapFree(GetProcessHeap(),0,This->buffer);
425                 }
426         }
427
428         if (This->notifies != NULL)
429                 HeapFree(GetProcessHeap(), 0, This->notifies);
430
431         HeapFree(GetProcessHeap(),0,This);
432
433         TRACE("(%p) released\n",This);
434         return 0;
435 }
436
437 DWORD DSOUND_CalcPlayPosition(IDirectSoundBufferImpl *This,
438                               DWORD state, DWORD pplay, DWORD pwrite, DWORD pmix, DWORD bmix)
439 {
440         DWORD bplay;
441
442         TRACE("primary playpos=%ld, mixpos=%ld\n", pplay, pmix);
443         TRACE("this mixpos=%ld, time=%ld\n", bmix, GetTickCount());
444
445         /* the actual primary play position (pplay) is always behind last mixed (pmix),
446          * unless the computer is too slow or something */
447         /* we need to know how far away we are from there */
448 #if 0 /* we'll never fill the primary entirely */
449         if (pmix == pplay) {
450                 if ((state == STATE_PLAYING) || (state == STATE_STOPPING)) {
451                         /* wow, the software mixer is really doing well,
452                          * seems the entire primary buffer is filled! */
453                         pmix += This->dsound->buflen;
454                 }
455                 /* else: the primary buffer is not playing, so probably empty */
456         }
457 #endif
458         if (pmix < pplay) pmix += This->dsound->buflen; /* wraparound */
459         pmix -= pplay;
460         /* detect buffer underrun */
461         if (pwrite < pplay) pwrite += This->dsound->buflen; /* wraparound */
462         pwrite -= pplay;
463         if (pmix > (ds_snd_queue_max * This->dsound->fraglen + pwrite + This->dsound->writelead)) {
464                 WARN("detected an underrun: primary queue was %ld\n",pmix);
465                 pmix = 0;
466         }
467         /* divide the offset by its sample size */
468         pmix /= This->dsound->wfx.nBlockAlign;
469         TRACE("primary back-samples=%ld\n",pmix);
470         /* adjust for our frequency */
471         pmix = (pmix * This->freqAdjust) >> DSOUND_FREQSHIFT;
472         /* multiply by our own sample size */
473         pmix *= This->wfx.nBlockAlign;
474         TRACE("this back-offset=%ld\n", pmix);
475         /* subtract from our last mixed position */
476         bplay = bmix;
477         while (bplay < pmix) bplay += This->buflen; /* wraparound */
478         bplay -= pmix;
479         if (This->leadin && ((bplay < This->startpos) || (bplay > bmix))) {
480                 /* seems we haven't started playing yet */
481                 TRACE("this still in lead-in phase\n");
482                 bplay = This->startpos;
483         }
484         /* return the result */
485         return bplay;
486 }
487
488 static HRESULT WINAPI IDirectSoundBufferImpl_GetCurrentPosition(
489         LPDIRECTSOUNDBUFFER8 iface,LPDWORD playpos,LPDWORD writepos
490 ) {
491         HRESULT hres;
492         ICOM_THIS(IDirectSoundBufferImpl,iface);
493         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
494         if (This->hwbuf) {
495                 hres=IDsDriverBuffer_GetPosition(This->hwbuf,playpos,writepos);
496                 if (hres != DS_OK) {
497                     WARN("IDsDriverBuffer_GetPosition failed\n");
498                     return hres;
499                 }
500         }
501         else {
502                 if (playpos && (This->state != STATE_PLAYING)) {
503                         /* we haven't been merged into the primary buffer (yet) */
504                         *playpos = This->buf_mixpos;
505                 }
506                 else if (playpos) {
507                         DWORD pplay, pwrite, lplay, splay, pstate;
508                         /* let's get this exact; first, recursively call GetPosition on the primary */
509                         EnterCriticalSection(&(This->dsound->mixlock));
510                         if (DSOUND_PrimaryGetPosition(This->dsound, &pplay, &pwrite) != DS_OK)
511                                 WARN("DSOUND_PrimaryGetPosition failed\n");
512                         /* detect HEL mode underrun */
513                         pstate = This->dsound->state;
514                         if (!(This->dsound->hwbuf || This->dsound->pwqueue)) {
515                                 TRACE("detected an underrun\n");
516                                 /* pplay = ? */
517                                 if (pstate == STATE_PLAYING)
518                                         pstate = STATE_STARTING;
519                                 else if (pstate == STATE_STOPPING)
520                                         pstate = STATE_STOPPED;
521                         }
522                         /* get data for ourselves while we still have the lock */
523                         pstate &= This->state;
524                         lplay = This->primary_mixpos;
525                         splay = This->buf_mixpos;
526                         if ((This->dsbd.dwFlags & DSBCAPS_GETCURRENTPOSITION2) || This->dsound->hwbuf) {
527                                 /* calculate play position using this */
528                                 *playpos = DSOUND_CalcPlayPosition(This, pstate, pplay, pwrite, lplay, splay);
529                         } else {
530                                 /* (unless the app isn't using GETCURRENTPOSITION2) */
531                                 /* don't know exactly how this should be handled...
532                                  * the docs says that play cursor is reported as directly
533                                  * behind write cursor, hmm... */
534                                 /* let's just do what might work for Half-Life */
535                                 DWORD wp;
536                                 wp = (This->dsound->pwplay + ds_hel_margin) * This->dsound->fraglen;
537                                 while (wp >= This->dsound->buflen)
538                                         wp -= This->dsound->buflen;
539                                 *playpos = DSOUND_CalcPlayPosition(This, pstate, wp, pwrite, lplay, splay);
540                         }
541                         LeaveCriticalSection(&(This->dsound->mixlock));
542                 }
543                 if (writepos) *writepos = This->buf_mixpos;
544         }
545         if (writepos) {
546                 if (This->state != STATE_STOPPED)
547                         /* apply the documented 10ms lead to writepos */
548                         *writepos += This->writelead;
549                 while (*writepos >= This->buflen) *writepos -= This->buflen;
550         }
551         if (playpos) This->last_playpos = *playpos;
552         TRACE("playpos = %ld, writepos = %ld (%p, time=%ld)\n", playpos?*playpos:0, writepos?*writepos:0, This, GetTickCount());
553         return DS_OK;
554 }
555
556 static HRESULT WINAPI IDirectSoundBufferImpl_GetStatus(
557         LPDIRECTSOUNDBUFFER8 iface,LPDWORD status
558 ) {
559         ICOM_THIS(IDirectSoundBufferImpl,iface);
560         TRACE("(%p,%p), thread is %04lx\n",This,status,GetCurrentThreadId());
561
562         if (status == NULL) {
563                 WARN("invalid parameter: status = NULL\n");
564                 return DSERR_INVALIDPARAM;
565         }
566
567         *status = 0;
568         if ((This->state == STATE_STARTING) || (This->state == STATE_PLAYING)) {
569                 *status |= DSBSTATUS_PLAYING;
570                 if (This->playflags & DSBPLAY_LOOPING)
571                         *status |= DSBSTATUS_LOOPING;
572         }
573
574         TRACE("status=%lx\n", *status);
575         return DS_OK;
576 }
577
578
579 static HRESULT WINAPI IDirectSoundBufferImpl_GetFormat(
580         LPDIRECTSOUNDBUFFER8 iface,LPWAVEFORMATEX lpwf,DWORD wfsize,LPDWORD wfwritten
581 ) {
582         ICOM_THIS(IDirectSoundBufferImpl,iface);
583         TRACE("(%p,%p,%ld,%p)\n",This,lpwf,wfsize,wfwritten);
584
585         if (wfsize>sizeof(This->wfx))
586                 wfsize = sizeof(This->wfx);
587         if (lpwf) {     /* NULL is valid */
588                 memcpy(lpwf,&(This->wfx),wfsize);
589                 if (wfwritten)
590                         *wfwritten = wfsize;
591         } else {
592                 if (wfwritten)
593                         *wfwritten = sizeof(This->wfx);
594                 else {
595                         WARN("invalid parameter: wfwritten == NULL\n");
596                         return DSERR_INVALIDPARAM;
597                 }
598         }
599
600         return DS_OK;
601 }
602
603 static HRESULT WINAPI IDirectSoundBufferImpl_Lock(
604         LPDIRECTSOUNDBUFFER8 iface,DWORD writecursor,DWORD writebytes,LPVOID lplpaudioptr1,LPDWORD audiobytes1,LPVOID lplpaudioptr2,LPDWORD audiobytes2,DWORD flags
605 ) {
606         HRESULT hres = DS_OK;
607         ICOM_THIS(IDirectSoundBufferImpl,iface);
608
609         TRACE("(%p,%ld,%ld,%p,%p,%p,%p,0x%08lx) at %ld\n",
610                 This,
611                 writecursor,
612                 writebytes,
613                 lplpaudioptr1,
614                 audiobytes1,
615                 lplpaudioptr2,
616                 audiobytes2,
617                 flags,
618                 GetTickCount()
619         );
620
621         if (flags & DSBLOCK_FROMWRITECURSOR) {
622                 DWORD writepos;
623                 /* GetCurrentPosition does too much magic to duplicate here */
624                 hres = IDirectSoundBufferImpl_GetCurrentPosition(iface, NULL, &writepos);
625                 if (hres != DS_OK) {
626                         WARN("IDirectSoundBufferImpl_GetCurrentPosition failed\n");
627                         return hres;
628                 }
629                 writecursor += writepos;
630         }
631         while (writecursor >= This->buflen)
632                 writecursor -= This->buflen;
633         if (flags & DSBLOCK_ENTIREBUFFER)
634                 writebytes = This->buflen;
635         if (writebytes > This->buflen)
636                 writebytes = This->buflen;
637
638         assert(audiobytes1!=audiobytes2);
639         assert(lplpaudioptr1!=lplpaudioptr2);
640
641         EnterCriticalSection(&(This->lock));
642
643         if ((writebytes == This->buflen) &&
644             ((This->state == STATE_STARTING) ||
645              (This->state == STATE_PLAYING)))
646                 /* some games, like Half-Life, try to be clever (not) and
647                  * keep one secondary buffer, and mix sounds into it itself,
648                  * locking the entire buffer every time... so we can just forget
649                  * about tracking the last-written-to-position... */
650                 This->probably_valid_to = (DWORD)-1;
651         else
652                 This->probably_valid_to = writecursor;
653
654         if (!(This->dsound->drvdesc.dwFlags & DSDDESC_DONTNEEDSECONDARYLOCK) && This->hwbuf) {
655                 hres = IDsDriverBuffer_Lock(This->hwbuf,
656                                      lplpaudioptr1, audiobytes1,
657                                      lplpaudioptr2, audiobytes2,
658                                      writecursor, writebytes,
659                                      0);
660                 if (hres != DS_OK) {
661                         WARN("IDsDriverBuffer_Lock failed\n");
662                         LeaveCriticalSection(&(This->lock));
663                         return hres;
664                 }
665         } else {
666                 BOOL remix = FALSE;
667                 if (writecursor+writebytes <= This->buflen) {
668                         *(LPBYTE*)lplpaudioptr1 = This->buffer->memory+writecursor;
669                         *audiobytes1 = writebytes;
670                         if (lplpaudioptr2)
671                                 *(LPBYTE*)lplpaudioptr2 = NULL;
672                         if (audiobytes2)
673                                 *audiobytes2 = 0;
674                         TRACE("->%ld.0\n",writebytes);
675                 } else {
676                         *(LPBYTE*)lplpaudioptr1 = This->buffer->memory+writecursor;
677                         *audiobytes1 = This->buflen-writecursor;
678                         if (lplpaudioptr2)
679                                 *(LPBYTE*)lplpaudioptr2 = This->buffer->memory;
680                         if (audiobytes2)
681                                 *audiobytes2 = writebytes-(This->buflen-writecursor);
682                         TRACE("->%ld.%ld\n",*audiobytes1,audiobytes2?*audiobytes2:0);
683                 }
684                 if (This->state == STATE_PLAYING) {
685                         /* if the segment between playpos and buf_mixpos is touched,
686                          * we need to cancel some mixing */
687                         /* we'll assume that the app always calls GetCurrentPosition before
688                          * locking a playing buffer, so that last_playpos is up-to-date */
689                         if (This->buf_mixpos >= This->last_playpos) {
690                                 if (This->buf_mixpos > writecursor &&
691                                     This->last_playpos < writecursor+writebytes)
692                                         remix = TRUE;
693                         }
694                         else {
695                                 if (This->buf_mixpos > writecursor ||
696                                     This->last_playpos < writecursor+writebytes)
697                                         remix = TRUE;
698                         }
699                         if (remix) {
700                                 TRACE("locking prebuffered region, ouch\n");
701                                 DSOUND_MixCancelAt(This, writecursor);
702                         }
703                 }
704         }
705
706         LeaveCriticalSection(&(This->lock));
707         return DS_OK;
708 }
709
710 static HRESULT WINAPI IDirectSoundBufferImpl_SetCurrentPosition(
711         LPDIRECTSOUNDBUFFER8 iface,DWORD newpos
712 ) {
713         HRESULT hres = DS_OK;
714         ICOM_THIS(IDirectSoundBufferImpl,iface);
715         TRACE("(%p,%ld)\n",This,newpos);
716
717         /* **** */
718         EnterCriticalSection(&(This->lock));
719
720         while (newpos >= This->buflen)
721                 newpos -= This->buflen;
722         This->buf_mixpos = newpos;
723         if (This->hwbuf) {
724                 hres = IDsDriverBuffer_SetPosition(This->hwbuf, This->buf_mixpos);
725                 if (hres != DS_OK)
726                         WARN("IDsDriverBuffer_SetPosition failed\n");
727         }
728
729         LeaveCriticalSection(&(This->lock));
730         /* **** */
731
732         return hres;
733 }
734
735 static HRESULT WINAPI IDirectSoundBufferImpl_SetPan(
736         LPDIRECTSOUNDBUFFER8 iface,LONG pan
737 ) {
738         HRESULT hres = DS_OK;
739         ICOM_THIS(IDirectSoundBufferImpl,iface);
740
741         TRACE("(%p,%ld)\n",This,pan);
742
743         if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT)) {
744                 WARN("invalid parameter: pan = %ld\n", pan);
745                 return DSERR_INVALIDPARAM;
746         }
747
748         /* You cannot use both pan and 3D controls */
749         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
750             (This->dsbd.dwFlags & DSBCAPS_CTRL3D)) {
751                 WARN("control unavailable\n");
752                 return DSERR_CONTROLUNAVAIL;
753         }
754
755         /* **** */
756         EnterCriticalSection(&(This->lock));
757
758         if (This->volpan.lPan != pan) {
759                 This->volpan.lPan = pan;
760                 DSOUND_RecalcVolPan(&(This->volpan));
761
762                 if (This->hwbuf) {
763                         hres = IDsDriverBuffer_SetVolumePan(This->hwbuf, &(This->volpan));
764                         if (hres != DS_OK)
765                                 WARN("IDsDriverBuffer_SetVolumePan failed\n");
766                 } else
767                         DSOUND_ForceRemix(This);
768         }
769
770         LeaveCriticalSection(&(This->lock));
771         /* **** */
772
773         return hres;
774 }
775
776 static HRESULT WINAPI IDirectSoundBufferImpl_GetPan(
777         LPDIRECTSOUNDBUFFER8 iface,LPLONG pan
778 ) {
779         ICOM_THIS(IDirectSoundBufferImpl,iface);
780         TRACE("(%p,%p)\n",This,pan);
781
782         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
783                 WARN("control unavailable\n");
784                 return DSERR_CONTROLUNAVAIL;
785         }
786
787         if (pan == NULL) {
788                 WARN("invalid parameter: pan = NULL\n");
789                 return DSERR_INVALIDPARAM;
790         }
791
792         *pan = This->volpan.lPan;
793
794         return DS_OK;
795 }
796
797 static HRESULT WINAPI IDirectSoundBufferImpl_Unlock(
798         LPDIRECTSOUNDBUFFER8 iface,LPVOID p1,DWORD x1,LPVOID p2,DWORD x2
799 ) {
800         ICOM_THIS(IDirectSoundBufferImpl,iface);
801         DWORD probably_valid_to;
802
803         TRACE("(%p,%p,%ld,%p,%ld)\n", This,p1,x1,p2,x2);
804
805         if (!(This->dsound->drvdesc.dwFlags & DSDDESC_DONTNEEDSECONDARYLOCK) && This->hwbuf) {
806                 HRESULT hres;
807                 hres = IDsDriverBuffer_Unlock(This->hwbuf, p1, x1, p2, x2);
808                 if (hres != DS_OK) {
809                         WARN("IDsDriverBuffer_Unlock failed\n");
810                         return hres;
811                 }
812         }
813
814         if (p2) probably_valid_to = (((LPBYTE)p2)-This->buffer->memory) + x2;
815         else probably_valid_to = (((LPBYTE)p1)-This->buffer->memory) + x1;
816         while (probably_valid_to >= This->buflen)
817                 probably_valid_to -= This->buflen;
818         if ((probably_valid_to == 0) && ((x1+x2) == This->buflen) &&
819             ((This->state == STATE_STARTING) ||
820              (This->state == STATE_PLAYING)))
821                 /* see IDirectSoundBufferImpl_Lock */
822                 probably_valid_to = (DWORD)-1;
823         This->probably_valid_to = probably_valid_to;
824
825         return DS_OK;
826 }
827
828 static HRESULT WINAPI IDirectSoundBufferImpl_Restore(
829         LPDIRECTSOUNDBUFFER8 iface
830 ) {
831         ICOM_THIS(IDirectSoundBufferImpl,iface);
832         FIXME("(%p):stub\n",This);
833         return DS_OK;
834 }
835
836 static HRESULT WINAPI IDirectSoundBufferImpl_GetFrequency(
837         LPDIRECTSOUNDBUFFER8 iface,LPDWORD freq
838 ) {
839         ICOM_THIS(IDirectSoundBufferImpl,iface);
840         TRACE("(%p,%p)\n",This,freq);
841
842         if (freq == NULL) {
843                 WARN("invalid parameter: freq = NULL\n");
844                 return DSERR_INVALIDPARAM;
845         }
846
847         *freq = This->freq;
848         TRACE("-> %ld\n", *freq);
849
850         return DS_OK;
851 }
852
853 static HRESULT WINAPI IDirectSoundBufferImpl_SetFX(
854         LPDIRECTSOUNDBUFFER8 iface,DWORD dwEffectsCount,LPDSEFFECTDESC pDSFXDesc,LPDWORD pdwResultCodes
855 ) {
856         ICOM_THIS(IDirectSoundBufferImpl,iface);
857         DWORD u;
858
859         FIXME("(%p,%lu,%p,%p): stub\n",This,dwEffectsCount,pDSFXDesc,pdwResultCodes);
860
861         if (pdwResultCodes)
862                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
863
864         WARN("control unavailable\n");
865         return DSERR_CONTROLUNAVAIL;
866 }
867
868 static HRESULT WINAPI IDirectSoundBufferImpl_AcquireResources(
869         LPDIRECTSOUNDBUFFER8 iface,DWORD dwFlags,DWORD dwEffectsCount,LPDWORD pdwResultCodes
870 ) {
871         ICOM_THIS(IDirectSoundBufferImpl,iface);
872         DWORD u;
873
874         FIXME("(%p,%08lu,%lu,%p): stub\n",This,dwFlags,dwEffectsCount,pdwResultCodes);
875
876         if (pdwResultCodes)
877                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
878
879         WARN("control unavailable\n");
880         return DSERR_CONTROLUNAVAIL;
881 }
882
883 static HRESULT WINAPI IDirectSoundBufferImpl_GetObjectInPath(
884         LPDIRECTSOUNDBUFFER8 iface,REFGUID rguidObject,DWORD dwIndex,REFGUID rguidInterface,LPVOID* ppObject
885 ) {
886         ICOM_THIS(IDirectSoundBufferImpl,iface);
887
888         FIXME("(%p,%s,%lu,%s,%p): stub\n",This,debugstr_guid(rguidObject),dwIndex,debugstr_guid(rguidInterface),ppObject);
889
890         WARN("control unavailable\n");
891         return DSERR_CONTROLUNAVAIL;
892 }
893
894 static HRESULT WINAPI IDirectSoundBufferImpl_Initialize(
895         LPDIRECTSOUNDBUFFER8 iface,LPDIRECTSOUND dsound,LPCDSBUFFERDESC dbsd
896 ) {
897         ICOM_THIS(IDirectSoundBufferImpl,iface);
898         FIXME("(%p,%p,%p):stub\n",This,dsound,dbsd);
899         DPRINTF("Re-Init!!!\n");
900         WARN("already initialized\n");
901         return DSERR_ALREADYINITIALIZED;
902 }
903
904 static HRESULT WINAPI IDirectSoundBufferImpl_GetCaps(
905         LPDIRECTSOUNDBUFFER8 iface,LPDSBCAPS caps
906 ) {
907         ICOM_THIS(IDirectSoundBufferImpl,iface);
908         TRACE("(%p)->(%p)\n",This,caps);
909
910         if (caps == NULL) {
911                 WARN("invalid parameter: caps == NULL\n");
912                 return DSERR_INVALIDPARAM;
913         }
914
915         if (caps->dwSize < sizeof(*caps)) {
916                 WARN("invalid parameter: caps->dwSize = %ld < %d\n",caps->dwSize, sizeof(*caps));
917                 return DSERR_INVALIDPARAM;
918         }
919
920         caps->dwFlags = This->dsbd.dwFlags;
921         if (This->hwbuf) caps->dwFlags |= DSBCAPS_LOCHARDWARE;
922         else caps->dwFlags |= DSBCAPS_LOCSOFTWARE;
923
924         caps->dwBufferBytes = This->buflen;
925
926         /* This value represents the speed of the "unlock" command.
927            As unlock is quite fast (it does not do anything), I put
928            4096 ko/s = 4 Mo / s */
929         /* FIXME: hwbuf speed */
930         caps->dwUnlockTransferRate = 4096;
931         caps->dwPlayCpuOverhead = 0;
932
933         return DS_OK;
934 }
935
936 static HRESULT WINAPI IDirectSoundBufferImpl_QueryInterface(
937         LPDIRECTSOUNDBUFFER8 iface,REFIID riid,LPVOID *ppobj
938 ) {
939         ICOM_THIS(IDirectSoundBufferImpl,iface);
940
941         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
942
943         if (ppobj == NULL) {
944                 WARN("invalid parameter\n");
945                 return E_INVALIDARG;
946         }
947
948         *ppobj = NULL;  /* assume failure */
949
950         if ( IsEqualGUID(riid, &IID_IUnknown) ||
951              IsEqualGUID(riid, &IID_IDirectSoundBuffer) ||
952              IsEqualGUID(riid, &IID_IDirectSoundBuffer8) ) {
953                 if (!This->dsb)
954                         SecondaryBufferImpl_Create(This, &(This->dsb));
955                 if (This->dsb) {
956                         IDirectSoundBuffer8_AddRef((LPDIRECTSOUNDBUFFER8)This->dsb);
957                         *ppobj = This->dsb;
958                         return S_OK;
959                 }
960                 WARN("IID_IDirectSoundBuffer\n");
961                 return E_NOINTERFACE;
962         }
963
964         if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ||
965              IsEqualGUID( &IID_IDirectSoundNotify8, riid ) ) {
966                 if (!This->notify)
967                         IDirectSoundNotifyImpl_Create(This, &(This->notify));
968                 if (This->notify) {
969                         IDirectSoundNotify_AddRef((LPDIRECTSOUNDNOTIFY)This->notify);
970                         *ppobj = This->notify;
971                         return S_OK;
972                 }
973                 WARN("IID_IDirectSoundNotify\n");
974                 return E_NOINTERFACE;
975         }
976
977         if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
978                 if (!This->ds3db)
979                         IDirectSound3DBufferImpl_Create(This, &(This->ds3db));
980                 if (This->ds3db) {
981                         IDirectSound3DBuffer_AddRef((LPDIRECTSOUND3DBUFFER)This->ds3db);
982                         *ppobj = This->ds3db;
983                         return S_OK;
984                 }
985                 WARN("IID_IDirectSound3DBuffer\n");
986                 return E_NOINTERFACE;
987         }
988
989         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
990                 ERR("app requested IDirectSound3DListener on secondary buffer\n");
991                 return E_NOINTERFACE;
992         }
993
994         if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
995                 /* only supported on hardware 3D secondary buffers */
996                 if (!(This->dsbd.dwFlags & DSBCAPS_PRIMARYBUFFER) &&
997                      (This->dsbd.dwFlags & DSBCAPS_CTRL3D) &&
998                      (This->hwbuf != NULL) ) {
999                         if (!This->iks)
1000                                 IKsBufferPropertySetImpl_Create(This, &(This->iks));
1001                         if (This->iks) {
1002                                 IKsPropertySet_AddRef((LPKSPROPERTYSET)*ppobj);
1003                                 *ppobj = This->iks;
1004                                 return S_OK;
1005                         }
1006                 }
1007                 WARN("IID_IKsPropertySet\n");
1008                 return E_NOINTERFACE;
1009         }
1010
1011         FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
1012
1013         return E_NOINTERFACE;
1014 }
1015
1016 static ICOM_VTABLE(IDirectSoundBuffer8) dsbvt =
1017 {
1018         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1019         IDirectSoundBufferImpl_QueryInterface,
1020         IDirectSoundBufferImpl_AddRef,
1021         IDirectSoundBufferImpl_Release,
1022         IDirectSoundBufferImpl_GetCaps,
1023         IDirectSoundBufferImpl_GetCurrentPosition,
1024         IDirectSoundBufferImpl_GetFormat,
1025         IDirectSoundBufferImpl_GetVolume,
1026         IDirectSoundBufferImpl_GetPan,
1027         IDirectSoundBufferImpl_GetFrequency,
1028         IDirectSoundBufferImpl_GetStatus,
1029         IDirectSoundBufferImpl_Initialize,
1030         IDirectSoundBufferImpl_Lock,
1031         IDirectSoundBufferImpl_Play,
1032         IDirectSoundBufferImpl_SetCurrentPosition,
1033         IDirectSoundBufferImpl_SetFormat,
1034         IDirectSoundBufferImpl_SetVolume,
1035         IDirectSoundBufferImpl_SetPan,
1036         IDirectSoundBufferImpl_SetFrequency,
1037         IDirectSoundBufferImpl_Stop,
1038         IDirectSoundBufferImpl_Unlock,
1039         IDirectSoundBufferImpl_Restore,
1040         IDirectSoundBufferImpl_SetFX,
1041         IDirectSoundBufferImpl_AcquireResources,
1042         IDirectSoundBufferImpl_GetObjectInPath
1043 };
1044
1045 HRESULT WINAPI IDirectSoundBufferImpl_Create(
1046         IDirectSoundImpl *ds,
1047         IDirectSoundBufferImpl **pdsb,
1048         LPCDSBUFFERDESC dsbd)
1049 {
1050         IDirectSoundBufferImpl *dsb;
1051         LPWAVEFORMATEX wfex = dsbd->lpwfxFormat;
1052         HRESULT err = DS_OK;
1053         DWORD capf = 0;
1054         int use_hw;
1055         TRACE("(%p,%p,%p)\n",ds,pdsb,dsbd);
1056
1057         if (dsbd->dwBufferBytes < DSBSIZE_MIN || dsbd->dwBufferBytes > DSBSIZE_MAX) {
1058                 WARN("invalid parameter: dsbd->dwBufferBytes = %ld\n", dsbd->dwBufferBytes);
1059                 *pdsb = NULL;
1060                 return DSERR_INVALIDPARAM; /* FIXME: which error? */
1061         }
1062
1063         dsb = (IDirectSoundBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*dsb));
1064
1065         if (dsb == 0) {
1066                 WARN("out of memory\n");
1067                 *pdsb = NULL;
1068                 return DSERR_OUTOFMEMORY;
1069         }
1070         dsb->ref = 0;
1071         dsb->dsb = 0;
1072         dsb->dsound = ds;
1073         dsb->lpVtbl = &dsbvt;
1074         dsb->iks = NULL;
1075
1076         memcpy(&dsb->dsbd, dsbd, sizeof(*dsbd));
1077         if (wfex)
1078                 memcpy(&dsb->wfx, wfex, sizeof(dsb->wfx));
1079
1080         TRACE("Created buffer at %p\n", dsb);
1081
1082         dsb->buflen = dsbd->dwBufferBytes;
1083         dsb->freq = dsbd->lpwfxFormat->nSamplesPerSec;
1084
1085         dsb->notify = NULL;
1086         dsb->notifies = NULL;
1087         dsb->nrofnotifies = 0;
1088         dsb->hwnotify = 0;
1089
1090         /* Check necessary hardware mixing capabilities */
1091         if (wfex->nChannels==2) capf |= DSCAPS_SECONDARYSTEREO;
1092         else capf |= DSCAPS_SECONDARYMONO;
1093         if (wfex->wBitsPerSample==16) capf |= DSCAPS_SECONDARY16BIT;
1094         else capf |= DSCAPS_SECONDARY8BIT;
1095
1096         use_hw = (ds->drvcaps.dwFlags & capf) == capf;
1097         TRACE("use_hw = 0x%08x, capf = 0x%08lx, ds->drvcaps.dwFlags = 0x%08lx\n", use_hw, capf, ds->drvcaps.dwFlags);
1098
1099         /* FIXME: check hardware sample rate mixing capabilities */
1100         /* FIXME: check app hints for software/hardware buffer (STATIC, LOCHARDWARE, etc) */
1101         /* FIXME: check whether any hardware buffers are left */
1102         /* FIXME: handle DSDHEAP_CREATEHEAP for hardware buffers */
1103
1104         /* Allocate system memory if applicable */
1105         if ((ds->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY) || !use_hw) {
1106                 dsb->buffer = HeapAlloc(GetProcessHeap(),0,sizeof(*(dsb->buffer)));
1107                 if (dsb->buffer == NULL) {
1108                         WARN("out of memory\n");
1109                         HeapFree(GetProcessHeap(),0,dsb);
1110                         *pdsb = NULL;
1111                         return DSERR_OUTOFMEMORY;
1112                 }
1113
1114                 dsb->buffer->memory = (LPBYTE)HeapAlloc(GetProcessHeap(),0,dsb->buflen);
1115                 if (dsb->buffer->memory == NULL) {
1116                         WARN("out of memory\n");
1117                         HeapFree(GetProcessHeap(),0,dsb->buffer);
1118                         HeapFree(GetProcessHeap(),0,dsb);
1119                         *pdsb = NULL;
1120                         return DSERR_OUTOFMEMORY;
1121                 }
1122                 dsb->buffer->ref = 1;
1123         }
1124
1125         /* Allocate the hardware buffer */
1126         if (use_hw) {
1127                 err = IDsDriver_CreateSoundBuffer(ds->driver,wfex,dsbd->dwFlags,0,
1128                                                   &(dsb->buflen),&(dsb->buffer->memory),
1129                                                   (LPVOID*)&(dsb->hwbuf));
1130                 /* fall back to software buffer on failure */
1131                 if (err != DS_OK) {
1132                         TRACE("IDsDriver_CreateSoundBuffer failed, falling back to software buffer\n");
1133                         use_hw = 0;
1134                         if (ds->drvdesc.dwFlags & DSDDESC_USESYSTEMMEMORY) {
1135                                 dsb->buffer = HeapAlloc(GetProcessHeap(),0,sizeof(*(dsb->buffer)));
1136                                 if (dsb->buffer == NULL) {
1137                                         WARN("out of memory\n");
1138                                         HeapFree(GetProcessHeap(),0,dsb);
1139                                         *pdsb = NULL;
1140                                         return DSERR_OUTOFMEMORY;
1141                                 }
1142
1143                                 dsb->buffer->memory = (LPBYTE)HeapAlloc(GetProcessHeap(),0,dsb->buflen);
1144                                 if (dsb->buffer->memory == NULL) {
1145                                         WARN("out of memory\n");
1146                                         HeapFree(GetProcessHeap(),0,dsb->buffer);
1147                                         HeapFree(GetProcessHeap(),0,dsb);
1148                                         *pdsb = NULL;
1149                                         return DSERR_OUTOFMEMORY;
1150                                 }
1151                                 dsb->buffer->ref = 1;
1152                         }
1153                 }
1154         }
1155
1156         /* calculate fragment size and write lead */
1157         DSOUND_RecalcFormat(dsb);
1158
1159         /* It's not necessary to initialize values to zero since */
1160         /* we allocated this structure with HEAP_ZERO_MEMORY... */
1161         dsb->playpos = 0;
1162         dsb->buf_mixpos = 0;
1163         dsb->state = STATE_STOPPED;
1164
1165         dsb->freqAdjust = (dsb->freq << DSOUND_FREQSHIFT) /
1166                 ds->wfx.nSamplesPerSec;
1167         dsb->nAvgBytesPerSec = dsb->freq *
1168                 dsbd->lpwfxFormat->nBlockAlign;
1169
1170         if (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D) {
1171                 dsb->ds3db_ds3db.dwSize = sizeof(DS3DBUFFER);
1172                 dsb->ds3db_ds3db.vPosition.x = 0.0;
1173                 dsb->ds3db_ds3db.vPosition.y = 0.0;
1174                 dsb->ds3db_ds3db.vPosition.z = 0.0;
1175                 dsb->ds3db_ds3db.vVelocity.x = 0.0;
1176                 dsb->ds3db_ds3db.vVelocity.y = 0.0;
1177                 dsb->ds3db_ds3db.vVelocity.z = 0.0;
1178                 dsb->ds3db_ds3db.dwInsideConeAngle = DS3D_DEFAULTCONEANGLE;
1179                 dsb->ds3db_ds3db.dwOutsideConeAngle = DS3D_DEFAULTCONEANGLE;
1180                 dsb->ds3db_ds3db.vConeOrientation.x = 0.0;
1181                 dsb->ds3db_ds3db.vConeOrientation.y = 0.0;
1182                 dsb->ds3db_ds3db.vConeOrientation.z = 0.0;
1183                 dsb->ds3db_ds3db.lConeOutsideVolume = DS3D_DEFAULTCONEOUTSIDEVOLUME;
1184                 dsb->ds3db_ds3db.flMinDistance = DS3D_DEFAULTMINDISTANCE;
1185                 dsb->ds3db_ds3db.flMaxDistance = DS3D_DEFAULTMAXDISTANCE;
1186                 dsb->ds3db_ds3db.dwMode = DS3DMODE_NORMAL;
1187
1188                 dsb->ds3db_need_recalc = FALSE;
1189                 DSOUND_Calc3DBuffer(dsb);
1190         } else
1191                 DSOUND_RecalcVolPan(&(dsb->volpan));
1192
1193         InitializeCriticalSection(&(dsb->lock));
1194         dsb->lock.DebugInfo->Spare[1] = (DWORD)"DSOUNDBUFFER_lock";
1195
1196         /* register buffer */
1197         RtlAcquireResourceExclusive(&(ds->lock), TRUE);
1198         if (!(dsbd->dwFlags & DSBCAPS_PRIMARYBUFFER)) {
1199                 IDirectSoundBufferImpl **newbuffers;
1200                 if (ds->buffers)
1201                         newbuffers = (IDirectSoundBufferImpl**)HeapReAlloc(GetProcessHeap(),0,ds->buffers,sizeof(IDirectSoundBufferImpl*)*(ds->nrofbuffers+1));
1202                 else
1203                         newbuffers = (IDirectSoundBufferImpl**)HeapAlloc(GetProcessHeap(),0,sizeof(IDirectSoundBufferImpl*)*(ds->nrofbuffers+1));
1204
1205                 if (newbuffers) {
1206                         ds->buffers = newbuffers;
1207                         ds->buffers[ds->nrofbuffers] = dsb;
1208                         ds->nrofbuffers++;
1209                         TRACE("buffer count is now %d\n", ds->nrofbuffers);
1210                 } else {
1211                         ERR("out of memory for buffer list! Current buffer count is %d\n", ds->nrofbuffers);
1212                         if (dsb->buffer->memory)
1213                                 HeapFree(GetProcessHeap(),0,dsb->buffer->memory);
1214                         if (dsb->buffer)
1215                                 HeapFree(GetProcessHeap(),0,dsb->buffer);
1216                         DeleteCriticalSection(&(dsb->lock));
1217                         RtlReleaseResource(&(ds->lock));
1218                         HeapFree(GetProcessHeap(),0,dsb);
1219                         *pdsb = NULL;
1220                         return DSERR_OUTOFMEMORY;
1221                 }
1222         }
1223         RtlReleaseResource(&(ds->lock));
1224         *pdsb = dsb;
1225         return S_OK;
1226 }
1227
1228 HRESULT WINAPI IDirectSoundBufferImpl_Destroy(
1229     IDirectSoundBufferImpl *pdsb)
1230 {
1231     TRACE("(%p)\n",pdsb);
1232
1233     /* This keeps the *_Destroy functions from possibly deleting
1234      * this object until it is ready to be deleted */
1235     IDirectSoundBufferImpl_AddRef((LPDIRECTSOUNDBUFFER8)pdsb);
1236
1237     if (pdsb->iks) {
1238         WARN("iks not NULL\n");
1239         IKsBufferPropertySetImpl_Destroy(pdsb->iks);
1240         pdsb->iks = NULL;
1241     }
1242
1243     if (pdsb->ds3db) {
1244         WARN("ds3db not NULL\n");
1245         IDirectSound3DBufferImpl_Destroy(pdsb->ds3db);
1246         pdsb->ds3db = NULL;
1247     }
1248
1249     if (pdsb->notify) {
1250         WARN("notify not NULL\n");
1251         IDirectSoundNotifyImpl_Destroy(pdsb->notify);
1252         pdsb->notify = NULL;
1253     }
1254
1255     if (pdsb->dsb) {
1256         WARN("dsb not NULL\n");
1257         SecondaryBufferImpl_Destroy(pdsb->dsb);
1258         pdsb->dsb = NULL;
1259     }
1260
1261     while (IDirectSoundBuffer8_Release((LPDIRECTSOUNDBUFFER8)pdsb) > 0);
1262
1263     return S_OK;
1264 }
1265
1266 /*******************************************************************************
1267  *              SecondaryBuffer
1268  */
1269
1270 static HRESULT WINAPI SecondaryBufferImpl_QueryInterface(
1271         LPDIRECTSOUNDBUFFER8 iface,REFIID riid,LPVOID *ppobj)
1272 {
1273         ICOM_THIS(SecondaryBufferImpl,iface);
1274         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
1275
1276         return IDirectSoundBufferImpl_QueryInterface((LPDIRECTSOUNDBUFFER8)This->dsb,riid,ppobj);
1277 }
1278
1279 static DWORD WINAPI SecondaryBufferImpl_AddRef(LPDIRECTSOUNDBUFFER8 iface)
1280 {
1281         ICOM_THIS(IDirectSoundBufferImpl,iface);
1282         DWORD ref;
1283         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
1284
1285         ref = InterlockedIncrement(&(This->ref));
1286         if (!ref) {
1287                 FIXME("thread-safety alert! AddRef-ing with a zero refcount!\n");
1288         }
1289         return ref;
1290 }
1291
1292 static DWORD WINAPI SecondaryBufferImpl_Release(LPDIRECTSOUNDBUFFER8 iface)
1293 {
1294         ICOM_THIS(IDirectSoundBufferImpl,iface);
1295         DWORD ref;
1296         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
1297
1298         ref = InterlockedDecrement(&(This->ref));
1299         if (!ref) {
1300                 This->dsb->dsb = NULL;
1301                 IDirectSoundBuffer_Release((LPDIRECTSOUNDBUFFER8)This->dsb);
1302                 HeapFree(GetProcessHeap(),0,This);
1303                 TRACE("(%p) released\n",This);
1304         }
1305         return ref;
1306 }
1307
1308 static HRESULT WINAPI SecondaryBufferImpl_GetCaps(
1309         LPDIRECTSOUNDBUFFER8 iface,LPDSBCAPS caps)
1310 {
1311         ICOM_THIS(SecondaryBufferImpl,iface);
1312         TRACE("(%p)->(%p)\n",This,caps);
1313
1314         return IDirectSoundBufferImpl_GetCaps((LPDIRECTSOUNDBUFFER8)This->dsb,caps);
1315 }
1316
1317 static HRESULT WINAPI SecondaryBufferImpl_GetCurrentPosition(
1318         LPDIRECTSOUNDBUFFER8 iface,LPDWORD playpos,LPDWORD writepos)
1319 {
1320         ICOM_THIS(SecondaryBufferImpl,iface);
1321         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
1322
1323         return IDirectSoundBufferImpl_GetCurrentPosition((LPDIRECTSOUNDBUFFER8)This->dsb,playpos,writepos);
1324 }
1325
1326 static HRESULT WINAPI SecondaryBufferImpl_GetFormat(
1327         LPDIRECTSOUNDBUFFER8 iface,LPWAVEFORMATEX lpwf,DWORD wfsize,LPDWORD wfwritten)
1328 {
1329         ICOM_THIS(SecondaryBufferImpl,iface);
1330         TRACE("(%p,%p,%ld,%p)\n",This,lpwf,wfsize,wfwritten);
1331
1332         return IDirectSoundBufferImpl_GetFormat((LPDIRECTSOUNDBUFFER8)This->dsb,lpwf,wfsize,wfwritten);
1333 }
1334
1335 static HRESULT WINAPI SecondaryBufferImpl_GetVolume(
1336         LPDIRECTSOUNDBUFFER8 iface,LPLONG vol)
1337 {
1338         ICOM_THIS(SecondaryBufferImpl,iface);
1339         TRACE("(%p,%p)\n",This,vol);
1340
1341         return IDirectSoundBufferImpl_GetVolume((LPDIRECTSOUNDBUFFER8)This->dsb,vol);
1342 }
1343
1344 static HRESULT WINAPI SecondaryBufferImpl_GetPan(
1345         LPDIRECTSOUNDBUFFER8 iface,LPLONG pan)
1346 {
1347         ICOM_THIS(SecondaryBufferImpl,iface);
1348         TRACE("(%p,%p)\n",This,pan);
1349
1350         return IDirectSoundBufferImpl_GetPan((LPDIRECTSOUNDBUFFER8)This->dsb,pan);
1351 }
1352
1353 static HRESULT WINAPI SecondaryBufferImpl_GetFrequency(
1354         LPDIRECTSOUNDBUFFER8 iface,LPDWORD freq)
1355 {
1356         ICOM_THIS(SecondaryBufferImpl,iface);
1357         TRACE("(%p,%p)\n",This,freq);
1358
1359         return IDirectSoundBufferImpl_GetFrequency((LPDIRECTSOUNDBUFFER8)This->dsb,freq);
1360 }
1361
1362 static HRESULT WINAPI SecondaryBufferImpl_GetStatus(
1363         LPDIRECTSOUNDBUFFER8 iface,LPDWORD status)
1364 {
1365         ICOM_THIS(SecondaryBufferImpl,iface);
1366         TRACE("(%p,%p)\n",This,status);
1367
1368         return IDirectSoundBufferImpl_GetStatus((LPDIRECTSOUNDBUFFER8)This->dsb,status);
1369 }
1370
1371 static HRESULT WINAPI SecondaryBufferImpl_Initialize(
1372         LPDIRECTSOUNDBUFFER8 iface,LPDIRECTSOUND dsound,LPCDSBUFFERDESC dbsd)
1373 {
1374         ICOM_THIS(SecondaryBufferImpl,iface);
1375         TRACE("(%p,%p,%p)\n",This,dsound,dbsd);
1376
1377         return IDirectSoundBufferImpl_Initialize((LPDIRECTSOUNDBUFFER8)This->dsb,dsound,dbsd);
1378 }
1379
1380 static HRESULT WINAPI SecondaryBufferImpl_Lock(
1381     LPDIRECTSOUNDBUFFER8 iface,
1382     DWORD writecursor,
1383     DWORD writebytes,
1384     LPVOID lplpaudioptr1,
1385     LPDWORD audiobytes1,
1386     LPVOID lplpaudioptr2,
1387     LPDWORD audiobytes2,
1388     DWORD dwFlags)
1389 {
1390     ICOM_THIS(SecondaryBufferImpl,iface);
1391     TRACE("(%p,%ld,%ld,%p,%p,%p,%p,0x%08lx)\n",
1392         This,writecursor,writebytes,lplpaudioptr1,audiobytes1,lplpaudioptr2,audiobytes2,dwFlags);
1393
1394     return IDirectSoundBufferImpl_Lock((LPDIRECTSOUNDBUFFER8)This->dsb,
1395         writecursor,writebytes,lplpaudioptr1,audiobytes1,lplpaudioptr2,audiobytes2,dwFlags);
1396 }
1397
1398 static HRESULT WINAPI SecondaryBufferImpl_Play(
1399         LPDIRECTSOUNDBUFFER8 iface,DWORD reserved1,DWORD reserved2,DWORD flags)
1400 {
1401         ICOM_THIS(SecondaryBufferImpl,iface);
1402         TRACE("(%p,%08lx,%08lx,%08lx)\n",This,reserved1,reserved2,flags);
1403
1404         return IDirectSoundBufferImpl_Play((LPDIRECTSOUNDBUFFER8)This->dsb,reserved1,reserved2,flags);
1405 }
1406
1407 static HRESULT WINAPI SecondaryBufferImpl_SetCurrentPosition(
1408         LPDIRECTSOUNDBUFFER8 iface,DWORD newpos)
1409 {
1410         ICOM_THIS(SecondaryBufferImpl,iface);
1411         TRACE("(%p,%ld)\n",This,newpos);
1412
1413         return IDirectSoundBufferImpl_SetCurrentPosition((LPDIRECTSOUNDBUFFER8)This->dsb,newpos);
1414 }
1415
1416 static HRESULT WINAPI SecondaryBufferImpl_SetFormat(
1417         LPDIRECTSOUNDBUFFER8 iface,LPCWAVEFORMATEX wfex)
1418 {
1419         ICOM_THIS(SecondaryBufferImpl,iface);
1420         TRACE("(%p,%p)\n",This,wfex);
1421
1422         return IDirectSoundBufferImpl_SetFormat((LPDIRECTSOUNDBUFFER8)This->dsb,wfex);
1423 }
1424
1425 static HRESULT WINAPI SecondaryBufferImpl_SetVolume(
1426         LPDIRECTSOUNDBUFFER8 iface,LONG vol)
1427 {
1428         ICOM_THIS(SecondaryBufferImpl,iface);
1429         TRACE("(%p,%ld)\n",This,vol);
1430
1431         return IDirectSoundBufferImpl_SetVolume((LPDIRECTSOUNDBUFFER8)This->dsb,vol);
1432 }
1433
1434 static HRESULT WINAPI SecondaryBufferImpl_SetPan(
1435         LPDIRECTSOUNDBUFFER8 iface,LONG pan)
1436 {
1437         ICOM_THIS(SecondaryBufferImpl,iface);
1438         TRACE("(%p,%ld)\n",This,pan);
1439
1440         return IDirectSoundBufferImpl_SetPan((LPDIRECTSOUNDBUFFER8)This->dsb,pan);
1441 }
1442
1443 static HRESULT WINAPI SecondaryBufferImpl_SetFrequency(
1444         LPDIRECTSOUNDBUFFER8 iface,DWORD freq)
1445 {
1446         ICOM_THIS(SecondaryBufferImpl,iface);
1447         TRACE("(%p,%ld)\n",This,freq);
1448
1449         return IDirectSoundBufferImpl_SetFrequency((LPDIRECTSOUNDBUFFER8)This->dsb,freq);
1450 }
1451
1452 static HRESULT WINAPI SecondaryBufferImpl_Stop(LPDIRECTSOUNDBUFFER8 iface)
1453 {
1454         ICOM_THIS(SecondaryBufferImpl,iface);
1455         TRACE("(%p)\n",This);
1456
1457         return IDirectSoundBufferImpl_Stop((LPDIRECTSOUNDBUFFER8)This->dsb);
1458 }
1459
1460 static HRESULT WINAPI SecondaryBufferImpl_Unlock(
1461     LPDIRECTSOUNDBUFFER8 iface,
1462     LPVOID lpvAudioPtr1,
1463     DWORD dwAudioBytes1,
1464     LPVOID lpvAudioPtr2,
1465     DWORD dwAudioBytes2)
1466 {
1467     ICOM_THIS(SecondaryBufferImpl,iface);
1468     TRACE("(%p,%p,%ld,%p,%ld)\n",
1469         This, lpvAudioPtr1, dwAudioBytes1, lpvAudioPtr2, dwAudioBytes2);
1470
1471     return IDirectSoundBufferImpl_Unlock((LPDIRECTSOUNDBUFFER8)This->dsb,
1472         lpvAudioPtr1,dwAudioBytes1,lpvAudioPtr2,dwAudioBytes2);
1473 }
1474
1475 static HRESULT WINAPI SecondaryBufferImpl_Restore(
1476         LPDIRECTSOUNDBUFFER8 iface)
1477 {
1478         ICOM_THIS(SecondaryBufferImpl,iface);
1479         TRACE("(%p)\n",This);
1480
1481         return IDirectSoundBufferImpl_Restore((LPDIRECTSOUNDBUFFER8)This->dsb);
1482 }
1483
1484 static HRESULT WINAPI SecondaryBufferImpl_SetFX(
1485         LPDIRECTSOUNDBUFFER8 iface,DWORD dwEffectsCount,LPDSEFFECTDESC pDSFXDesc,LPDWORD pdwResultCodes)
1486 {
1487         ICOM_THIS(SecondaryBufferImpl,iface);
1488         TRACE("(%p,%lu,%p,%p)\n",This,dwEffectsCount,pDSFXDesc,pdwResultCodes);
1489
1490         return IDirectSoundBufferImpl_SetFX((LPDIRECTSOUNDBUFFER8)This->dsb,dwEffectsCount,pDSFXDesc,pdwResultCodes);
1491 }
1492
1493 static HRESULT WINAPI SecondaryBufferImpl_AcquireResources(
1494         LPDIRECTSOUNDBUFFER8 iface,DWORD dwFlags,DWORD dwEffectsCount,LPDWORD pdwResultCodes)
1495 {
1496         ICOM_THIS(SecondaryBufferImpl,iface);
1497         TRACE("(%p,%08lu,%lu,%p)\n",This,dwFlags,dwEffectsCount,pdwResultCodes);
1498
1499         return IDirectSoundBufferImpl_AcquireResources((LPDIRECTSOUNDBUFFER8)This->dsb,dwFlags,dwEffectsCount,pdwResultCodes);
1500 }
1501
1502 static HRESULT WINAPI SecondaryBufferImpl_GetObjectInPath(
1503         LPDIRECTSOUNDBUFFER8 iface,REFGUID rguidObject,DWORD dwIndex,REFGUID rguidInterface,LPVOID* ppObject)
1504 {
1505         ICOM_THIS(SecondaryBufferImpl,iface);
1506         TRACE("(%p,%s,%lu,%s,%p)\n",This,debugstr_guid(rguidObject),dwIndex,debugstr_guid(rguidInterface),ppObject);
1507
1508         return IDirectSoundBufferImpl_GetObjectInPath((LPDIRECTSOUNDBUFFER8)This->dsb,rguidObject,dwIndex,rguidInterface,ppObject);
1509 }
1510
1511 static ICOM_VTABLE(IDirectSoundBuffer8) sbvt =
1512 {
1513         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1514         SecondaryBufferImpl_QueryInterface,
1515         SecondaryBufferImpl_AddRef,
1516         SecondaryBufferImpl_Release,
1517         SecondaryBufferImpl_GetCaps,
1518         SecondaryBufferImpl_GetCurrentPosition,
1519         SecondaryBufferImpl_GetFormat,
1520         SecondaryBufferImpl_GetVolume,
1521         SecondaryBufferImpl_GetPan,
1522         SecondaryBufferImpl_GetFrequency,
1523         SecondaryBufferImpl_GetStatus,
1524         SecondaryBufferImpl_Initialize,
1525         SecondaryBufferImpl_Lock,
1526         SecondaryBufferImpl_Play,
1527         SecondaryBufferImpl_SetCurrentPosition,
1528         SecondaryBufferImpl_SetFormat,
1529         SecondaryBufferImpl_SetVolume,
1530         SecondaryBufferImpl_SetPan,
1531         SecondaryBufferImpl_SetFrequency,
1532         SecondaryBufferImpl_Stop,
1533         SecondaryBufferImpl_Unlock,
1534         SecondaryBufferImpl_Restore,
1535         SecondaryBufferImpl_SetFX,
1536         SecondaryBufferImpl_AcquireResources,
1537         SecondaryBufferImpl_GetObjectInPath
1538 };
1539
1540 HRESULT WINAPI SecondaryBufferImpl_Create(
1541         IDirectSoundBufferImpl *dsb,
1542         SecondaryBufferImpl **psb)
1543 {
1544         SecondaryBufferImpl *sb;
1545         TRACE("(%p,%p)\n",dsb,psb);
1546
1547         sb = (SecondaryBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*sb));
1548
1549         if (sb == 0) {
1550                 WARN("out of memory\n");
1551                 *psb = NULL;
1552                 return DSERR_OUTOFMEMORY;
1553         }
1554         sb->ref = 0;
1555         sb->dsb = dsb;
1556         sb->lpVtbl = &sbvt;
1557
1558         IDirectSoundBuffer8_AddRef((LPDIRECTSOUNDBUFFER8)dsb);
1559         *psb = sb;
1560         return S_OK;
1561 }
1562
1563 HRESULT WINAPI SecondaryBufferImpl_Destroy(
1564     SecondaryBufferImpl *pdsb)
1565 {
1566     TRACE("(%p)\n",pdsb);
1567
1568     while (SecondaryBufferImpl_Release((LPDIRECTSOUNDBUFFER8)pdsb) > 0);
1569
1570     return S_OK;
1571 }