Fixed a race condition on RPC worker thread creation, and a typo.
[wine] / dlls / dsound / primary.c
1 /*                      DirectSound
2  *
3  * Copyright 1998 Marcus Meissner
4  * Copyright 1998 Rob Riggs
5  * Copyright 2000-2002 TransGaming Technologies, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include <assert.h>
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <sys/fcntl.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #include <stdlib.h>
31 #include <string.h>
32 #include <math.h>       /* Insomnia - pow() function */
33
34 #include "windef.h"
35 #include "winbase.h"
36 #include "wingdi.h"
37 #include "winuser.h"
38 #include "winerror.h"
39 #include "mmsystem.h"
40 #include "winternl.h"
41 #include "mmddk.h"
42 #include "wine/windef16.h"
43 #include "wine/debug.h"
44 #include "dsound.h"
45 #include "dsdriver.h"
46 #include "dsound_private.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
49
50 void DSOUND_RecalcPrimary(IDirectSoundImpl *This)
51 {
52         DWORD sw;
53
54         sw = This->wfx.nChannels * (This->wfx.wBitsPerSample / 8);
55         if (This->hwbuf) {
56                 DWORD fraglen;
57                 /* let fragment size approximate the timer delay */
58                 fraglen = (This->wfx.nSamplesPerSec * DS_TIME_DEL / 1000) * sw;
59                 /* reduce fragment size until an integer number of them fits in the buffer */
60                 /* (FIXME: this may or may not be a good idea) */
61                 while (This->buflen % fraglen) fraglen -= sw;
62                 This->fraglen = fraglen;
63                 TRACE("fraglen=%ld\n", This->fraglen);
64         }
65         /* calculate the 10ms write lead */
66         This->writelead = (This->wfx.nSamplesPerSec / 100) * sw;
67 }
68
69 static HRESULT DSOUND_PrimaryOpen(IDirectSoundImpl *This)
70 {
71         HRESULT err = DS_OK;
72
73         /* are we using waveOut stuff? */
74         if (!This->hwbuf) {
75                 LPBYTE newbuf;
76                 DWORD buflen;
77                 HRESULT merr = DS_OK;
78                 /* Start in pause mode, to allow buffers to get filled */
79                 waveOutPause(This->hwo);
80                 if (This->state == STATE_PLAYING) This->state = STATE_STARTING;
81                 else if (This->state == STATE_STOPPING) This->state = STATE_STOPPED;
82                 /* use fragments of 10ms (1/100s) each (which should get us within
83                  * the documented write cursor lead of 10-15ms) */
84                 buflen = ((This->wfx.nAvgBytesPerSec / 100) & ~3) * DS_HEL_FRAGS;
85                 TRACE("desired buflen=%ld, old buffer=%p\n", buflen, This->buffer);
86                 /* reallocate emulated primary buffer */
87                 newbuf = (LPBYTE)HeapReAlloc(GetProcessHeap(),0,This->buffer,buflen);
88                 if (newbuf == NULL) {
89                         ERR("failed to allocate primary buffer\n");
90                         merr = DSERR_OUTOFMEMORY;
91                         /* but the old buffer might still exist and must be re-prepared */
92                 } else {
93                         This->buffer = newbuf;
94                         This->buflen = buflen;
95                 }
96                 if (This->buffer) {
97                         unsigned c;
98
99                         This->fraglen = This->buflen / DS_HEL_FRAGS;
100
101                         /* prepare fragment headers */
102                         for (c=0; c<DS_HEL_FRAGS; c++) {
103                                 This->pwave[c]->lpData = This->buffer + c*This->fraglen;
104                                 This->pwave[c]->dwBufferLength = This->fraglen;
105                                 This->pwave[c]->dwUser = (DWORD)This;
106                                 This->pwave[c]->dwFlags = 0;
107                                 This->pwave[c]->dwLoops = 0;
108                                 err = mmErr(waveOutPrepareHeader(This->hwo,This->pwave[c],sizeof(WAVEHDR)));
109                                 if (err != DS_OK) {
110                                         while (c--)
111                                                 waveOutUnprepareHeader(This->hwo,This->pwave[c],sizeof(WAVEHDR));
112                                         break;
113                                 }
114                         }
115
116                         This->pwplay = 0;
117                         This->pwwrite = 0;
118                         This->pwqueue = 0;
119                         memset(This->buffer, (This->wfx.wBitsPerSample == 16) ? 0 : 128, This->buflen);
120                         TRACE("fraglen=%ld\n", This->fraglen);
121                         DSOUND_WaveQueue(This, (DWORD)-1);
122                 }
123                 if ((err == DS_OK) && (merr != DS_OK))
124                         err = merr;
125         }
126         return err;
127 }
128
129
130 static void DSOUND_PrimaryClose(IDirectSoundImpl *This)
131 {
132         /* are we using waveOut stuff? */
133         if (!This->hwbuf) {
134                 unsigned c;
135
136                 This->pwqueue = (DWORD)-1; /* resetting queues */
137                 waveOutReset(This->hwo);
138                 for (c=0; c<DS_HEL_FRAGS; c++)
139                         waveOutUnprepareHeader(This->hwo, This->pwave[c], sizeof(WAVEHDR));
140                 This->pwqueue = 0;
141         }
142 }
143
144 HRESULT DSOUND_PrimaryCreate(IDirectSoundImpl *This)
145 {
146         HRESULT err = DS_OK;
147
148         This->buflen = This->wfx.nAvgBytesPerSec;
149
150         /* FIXME: verify that hardware capabilities (DSCAPS_PRIMARY flags) match */
151
152         if (This->driver) {
153                 err = IDsDriver_CreateSoundBuffer(This->driver,&(This->wfx),
154                                                   DSBCAPS_PRIMARYBUFFER,0,
155                                                   &(This->buflen),&(This->buffer),
156                                                   (LPVOID*)&(This->hwbuf));
157         }
158         if (!This->hwbuf) {
159                 /* Allocate memory for HEL buffer headers */
160                 unsigned c;
161                 for (c=0; c<DS_HEL_FRAGS; c++) {
162                         This->pwave[c] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(WAVEHDR));
163                         if (!This->pwave[c]) {
164                                 /* Argh, out of memory */
165                                 while (c--) {
166                                         HeapFree(GetProcessHeap(),0,This->pwave[c]);
167                                 }
168                                 err=DSERR_OUTOFMEMORY;
169                                 break;
170                         }
171                 }
172         }
173         if (err == DS_OK)
174                 err = DSOUND_PrimaryOpen(This);
175         if (err != DS_OK)
176                 return err;
177         /* calculate fragment size and write lead */
178         DSOUND_RecalcPrimary(This);
179         This->state = STATE_STOPPED;
180         return DS_OK;
181 }
182
183 HRESULT DSOUND_PrimaryDestroy(IDirectSoundImpl *This)
184 {
185         DSOUND_PrimaryClose(This);
186         if (This->hwbuf) {
187                 if (IDsDriverBuffer_Release(This->hwbuf) == 0)
188                         This->hwbuf = 0;
189         } else {
190                 unsigned c;
191                 for (c=0; c<DS_HEL_FRAGS; c++) {
192                         HeapFree(GetProcessHeap(),0,This->pwave[c]);
193                 }
194         }
195         return DS_OK;
196 }
197
198 HRESULT DSOUND_PrimaryPlay(IDirectSoundImpl *This)
199 {
200         HRESULT err = DS_OK;
201         if (This->hwbuf)
202                 err = IDsDriverBuffer_Play(This->hwbuf, 0, 0, DSBPLAY_LOOPING);
203         else
204                 err = mmErr(waveOutRestart(This->hwo));
205         return err;
206 }
207
208 HRESULT DSOUND_PrimaryStop(IDirectSoundImpl *This)
209 {
210         HRESULT err = DS_OK;
211
212         TRACE("\n");
213
214         if (This->hwbuf) {
215                 err = IDsDriverBuffer_Stop(This->hwbuf);
216                 if (err == DSERR_BUFFERLOST) {
217                         DWORD flags = CALLBACK_FUNCTION;
218                         if (ds_hw_accel != DS_HW_ACCEL_EMULATION)
219                                 flags |= WAVE_DIRECTSOUND;
220                         /* Wine-only: the driver wants us to reopen the device */
221                         /* FIXME: check for errors */
222                         IDsDriverBuffer_Release(This->hwbuf);
223                         waveOutClose(This->hwo);
224                         This->hwo = 0;
225                         err = mmErr(waveOutOpen(&(This->hwo), This->drvdesc.dnDevNode,
226                                                 &(This->wfx), (DWORD)DSOUND_callback, (DWORD)This,
227                                                 flags));
228                         if (err == DS_OK)
229                                 err = IDsDriver_CreateSoundBuffer(This->driver,&(This->wfx),
230                                                                   DSBCAPS_PRIMARYBUFFER,0,
231                                                                   &(This->buflen),&(This->buffer),
232                                                                   (LPVOID)&(This->hwbuf));
233                 }
234         }
235         else
236                 err = mmErr(waveOutPause(This->hwo));
237         return err;
238 }
239
240 HRESULT DSOUND_PrimaryGetPosition(IDirectSoundImpl *This, LPDWORD playpos, LPDWORD writepos)
241 {
242         if (This->hwbuf) {
243                 HRESULT err=IDsDriverBuffer_GetPosition(This->hwbuf,playpos,writepos);
244                 if (err) return err;
245         }
246         else {
247                 if (playpos) {
248                         MMTIME mtime;
249                         mtime.wType = TIME_BYTES;
250                         waveOutGetPosition(This->hwo, &mtime, sizeof(mtime));
251                         mtime.u.cb = mtime.u.cb % This->buflen;
252                         *playpos = mtime.u.cb;
253                 }
254                 if (writepos) {
255                         /* the writepos should only be used by apps with WRITEPRIMARY priority,
256                          * in which case our software mixer is disabled anyway */
257                         *writepos = (This->pwplay + ds_hel_margin) * This->fraglen;
258                         while (*writepos >= This->buflen)
259                                 *writepos -= This->buflen;
260                 }
261         }
262         TRACE("playpos = %ld, writepos = %ld (%p, time=%ld)\n", playpos?*playpos:0, writepos?*writepos:0, This, GetTickCount());
263         return DS_OK;
264 }
265
266
267 /*******************************************************************************
268  *              IDirectSoundBuffer
269  */
270 /* This sets this format for the <em>Primary Buffer Only</em> */
271 /* See file:///cdrom/sdk52/docs/worddoc/dsound.doc page 120 */
272 static HRESULT WINAPI PrimaryBufferImpl_SetFormat(
273         LPDIRECTSOUNDBUFFER8 iface,LPWAVEFORMATEX wfex
274 ) {
275         ICOM_THIS(PrimaryBufferImpl,iface);
276         IDirectSoundImpl* dsound = This->dsound;
277         IDirectSoundBufferImpl** dsb;
278         HRESULT err = DS_OK;
279         int                     i;
280
281         if (This->dsound->priolevel == DSSCL_NORMAL) {
282                 TRACE("failed priority check!\n");
283                 return DSERR_PRIOLEVELNEEDED;
284         }
285
286         /* Let's be pedantic! */
287         if (wfex == NULL) {
288                 TRACE("wfex==NULL!\n");
289                 return DSERR_INVALIDPARAM;
290         }
291         TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld,"
292               "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
293               wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
294               wfex->nAvgBytesPerSec, wfex->nBlockAlign,
295               wfex->wBitsPerSample, wfex->cbSize);
296
297         if ((wfex->wFormatTag != WAVE_FORMAT_PCM) ||
298             (wfex->nChannels < 1) || (wfex->nChannels > 2) ||
299             (wfex->nSamplesPerSec < 1) ||
300             ((wfex->wBitsPerSample != 8) && (wfex->wBitsPerSample != 16))) {
301                 TRACE("unsupported format!\n");
302                 return DSERR_INVALIDPARAM;
303         }
304
305         /* **** */
306         RtlAcquireResourceExclusive(&(dsound->lock), TRUE);
307
308         if (dsound->wfx.nSamplesPerSec != wfex->nSamplesPerSec) {
309                 dsb = dsound->buffers;
310                 for (i = 0; i < dsound->nrofbuffers; i++, dsb++) {
311                         /* **** */
312                         EnterCriticalSection(&((*dsb)->lock));
313
314                         (*dsb)->freqAdjust = ((*dsb)->freq << DSOUND_FREQSHIFT) /
315                                 wfex->nSamplesPerSec;
316
317                         LeaveCriticalSection(&((*dsb)->lock));
318                         /* **** */
319                 }
320         }
321
322         dsound->wfx.nSamplesPerSec = wfex->nSamplesPerSec;
323         dsound->wfx.nChannels = wfex->nChannels;
324         dsound->wfx.wBitsPerSample = wfex->wBitsPerSample;
325         dsound->wfx.nBlockAlign = dsound->wfx.wBitsPerSample / 8 * dsound->wfx.nChannels;
326         dsound->wfx.nAvgBytesPerSec =
327                 dsound->wfx.nSamplesPerSec * dsound->wfx.nBlockAlign;
328
329         if (dsound->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMSETFORMAT) {
330                 DWORD flags = CALLBACK_FUNCTION;
331                 if (ds_hw_accel != DS_HW_ACCEL_EMULATION)
332                         flags |= WAVE_DIRECTSOUND;
333                 /* FIXME: check for errors */
334                 DSOUND_PrimaryClose(dsound);
335                 waveOutClose(dsound->hwo);
336                 dsound->hwo = 0;
337                 err = mmErr(waveOutOpen(&(dsound->hwo), dsound->drvdesc.dnDevNode,
338                                         &(dsound->wfx), (DWORD)DSOUND_callback, (DWORD)dsound,
339                                         flags));
340                 if (err == DS_OK)
341                     DSOUND_PrimaryOpen(dsound);
342         }
343         if (dsound->hwbuf) {
344                 err = IDsDriverBuffer_SetFormat(dsound->hwbuf, &(dsound->wfx));
345                 if (err == DSERR_BUFFERLOST) {
346                         /* Wine-only: the driver wants us to recreate the HW buffer */
347                         IDsDriverBuffer_Release(dsound->hwbuf);
348                         err = IDsDriver_CreateSoundBuffer(dsound->driver,&(dsound->wfx),
349                                                           DSBCAPS_PRIMARYBUFFER,0,
350                                                           &(dsound->buflen),&(dsound->buffer),
351                                                           (LPVOID)&(dsound->hwbuf));
352                         if (dsound->state == STATE_PLAYING) dsound->state = STATE_STARTING;
353                         else if (dsound->state == STATE_STOPPING) dsound->state = STATE_STOPPED;
354                 }
355                 /* FIXME: should we set err back to DS_OK in all cases ? */
356         }
357         DSOUND_RecalcPrimary(dsound);
358
359         RtlReleaseResource(&(dsound->lock));
360         /* **** */
361
362         return err;
363 }
364
365 static HRESULT WINAPI PrimaryBufferImpl_SetVolume(
366         LPDIRECTSOUNDBUFFER8 iface,LONG vol
367 ) {
368         ICOM_THIS(PrimaryBufferImpl,iface);
369         IDirectSoundImpl* dsound = This->dsound;
370         LONG oldVol;
371
372         TRACE("(%p,%ld)\n",This,vol);
373
374         /* I'm not sure if we need this for primary buffer */
375         if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
376                 return DSERR_CONTROLUNAVAIL;
377
378         if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN))
379                 return DSERR_INVALIDPARAM;
380
381         /* **** */
382         EnterCriticalSection(&(dsound->mixlock));
383
384         oldVol = dsound->volpan.lVolume;
385         dsound->volpan.lVolume = vol;
386         DSOUND_RecalcVolPan(&dsound->volpan);
387
388         if (vol != oldVol) {
389                 if (dsound->hwbuf) {
390                         IDsDriverBuffer_SetVolumePan(dsound->hwbuf, &(dsound->volpan));
391                 }
392                 else {
393 #if 0 /* should we really do this? */
394                         /* the DS volume ranges from 0 (max, 0dB attenuation) to -10000 (min, 100dB attenuation) */
395                         /* the MM volume ranges from 0 to 0xffff in an unspecified logarithmic scale */
396                         WORD cvol = 0xffff + vol*6 + vol/2;
397                         DWORD vol = cvol | ((DWORD)cvol << 16)
398                         waveOutSetVolume(dsound->hwo, vol);
399 #endif
400                 }
401         }
402
403         LeaveCriticalSection(&(dsound->mixlock));
404         /* **** */
405
406         return DS_OK;
407 }
408
409 static HRESULT WINAPI PrimaryBufferImpl_GetVolume(
410         LPDIRECTSOUNDBUFFER8 iface,LPLONG vol
411 ) {
412         ICOM_THIS(PrimaryBufferImpl,iface);
413         TRACE("(%p,%p)\n",This,vol);
414
415         if (vol == NULL)
416                 return DSERR_INVALIDPARAM;
417
418         *vol = This->dsound->volpan.lVolume;
419         return DS_OK;
420 }
421
422 static HRESULT WINAPI PrimaryBufferImpl_SetFrequency(
423         LPDIRECTSOUNDBUFFER8 iface,DWORD freq
424 ) {
425         ICOM_THIS(PrimaryBufferImpl,iface);
426
427         TRACE("(%p,%ld)\n",This,freq);
428
429         /* You cannot set the frequency of the primary buffer */
430         return DSERR_CONTROLUNAVAIL;
431 }
432
433 static HRESULT WINAPI PrimaryBufferImpl_Play(
434         LPDIRECTSOUNDBUFFER8 iface,DWORD reserved1,DWORD reserved2,DWORD flags
435 ) {
436         ICOM_THIS(PrimaryBufferImpl,iface);
437         IDirectSoundImpl* dsound = This->dsound;
438
439         TRACE("(%p,%08lx,%08lx,%08lx)\n",
440                 This,reserved1,reserved2,flags
441         );
442
443         if (!(flags & DSBPLAY_LOOPING))
444                 return DSERR_INVALIDPARAM;
445
446         /* **** */
447         EnterCriticalSection(&(dsound->mixlock));
448
449         if (dsound->state == STATE_STOPPED)
450                 dsound->state = STATE_STARTING;
451         else if (dsound->state == STATE_STOPPING)
452                 dsound->state = STATE_PLAYING;
453
454         LeaveCriticalSection(&(dsound->mixlock));
455         /* **** */
456
457         return DS_OK;
458 }
459
460 static HRESULT WINAPI PrimaryBufferImpl_Stop(LPDIRECTSOUNDBUFFER8 iface)
461 {
462         ICOM_THIS(PrimaryBufferImpl,iface);
463         IDirectSoundImpl* dsound = This->dsound;
464
465         TRACE("(%p)\n",This);
466
467         /* **** */
468         EnterCriticalSection(&(dsound->mixlock));
469
470         if (dsound->state == STATE_PLAYING)
471                 dsound->state = STATE_STOPPING;
472         else if (dsound->state == STATE_STARTING)
473                 dsound->state = STATE_STOPPED;
474
475         LeaveCriticalSection(&(dsound->mixlock));
476         /* **** */
477
478         return DS_OK;
479 }
480
481 static DWORD WINAPI PrimaryBufferImpl_AddRef(LPDIRECTSOUNDBUFFER8 iface) {
482         ICOM_THIS(PrimaryBufferImpl,iface);
483         DWORD ref;
484
485         TRACE("(%p) ref was %ld, thread is %lx\n",This, This->ref, GetCurrentThreadId());
486
487         ref = InterlockedIncrement(&(This->ref));
488         if (!ref) {
489                 FIXME("thread-safety alert! AddRef-ing with a zero refcount!\n");
490         }
491         return ref;
492 }
493 static DWORD WINAPI PrimaryBufferImpl_Release(LPDIRECTSOUNDBUFFER8 iface) {
494         ICOM_THIS(PrimaryBufferImpl,iface);
495         DWORD ref;
496
497         TRACE("(%p) ref was %ld, thread is %lx\n",This, This->ref, GetCurrentThreadId());
498
499         ref = InterlockedDecrement(&(This->ref));
500         if (ref) return ref;
501
502         IDirectSound_Release((LPDIRECTSOUND)This->dsound);
503
504 #if 0
505         if (This->iks) {
506                 HeapFree(GetProcessHeap(), 0, This->iks);
507         }
508 #endif
509
510         HeapFree(GetProcessHeap(),0,This);
511
512         return 0;
513 }
514
515 static HRESULT WINAPI PrimaryBufferImpl_GetCurrentPosition(
516         LPDIRECTSOUNDBUFFER8 iface,LPDWORD playpos,LPDWORD writepos
517 ) {
518         ICOM_THIS(PrimaryBufferImpl,iface);
519         IDirectSoundImpl* dsound = This->dsound;
520
521         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
522         DSOUND_PrimaryGetPosition(dsound, playpos, writepos);
523         if (writepos) {
524                 if (dsound->state != STATE_STOPPED)
525                         /* apply the documented 10ms lead to writepos */
526                         *writepos += dsound->writelead;
527                 while (*writepos >= dsound->buflen) *writepos -= dsound->buflen;
528         }
529         TRACE("playpos = %ld, writepos = %ld (%p, time=%ld)\n", playpos?*playpos:0, writepos?*writepos:0, This, GetTickCount());
530         return DS_OK;
531 }
532
533 static HRESULT WINAPI PrimaryBufferImpl_GetStatus(
534         LPDIRECTSOUNDBUFFER8 iface,LPDWORD status
535 ) {
536         ICOM_THIS(PrimaryBufferImpl,iface);
537         TRACE("(%p,%p), thread is %lx\n",This,status,GetCurrentThreadId());
538
539         if (status == NULL)
540                 return DSERR_INVALIDPARAM;
541
542         *status = 0;
543         if ((This->dsound->state == STATE_STARTING) ||
544             (This->dsound->state == STATE_PLAYING))
545                 *status |= DSBSTATUS_PLAYING | DSBSTATUS_LOOPING;
546
547         TRACE("status=%lx\n", *status);
548         return DS_OK;
549 }
550
551
552 static HRESULT WINAPI PrimaryBufferImpl_GetFormat(
553         LPDIRECTSOUNDBUFFER8 iface,LPWAVEFORMATEX lpwf,DWORD wfsize,LPDWORD wfwritten
554 ) {
555         ICOM_THIS(PrimaryBufferImpl,iface);
556         TRACE("(%p,%p,%ld,%p)\n",This,lpwf,wfsize,wfwritten);
557
558         if (wfsize>sizeof(This->dsound->wfx))
559                 wfsize = sizeof(This->dsound->wfx);
560         if (lpwf) {     /* NULL is valid */
561                 memcpy(lpwf,&(This->dsound->wfx),wfsize);
562                 if (wfwritten)
563                         *wfwritten = wfsize;
564         } else
565                 if (wfwritten)
566                         *wfwritten = sizeof(This->dsound->wfx);
567                 else
568                         return DSERR_INVALIDPARAM;
569
570         return DS_OK;
571 }
572
573 static HRESULT WINAPI PrimaryBufferImpl_Lock(
574         LPDIRECTSOUNDBUFFER8 iface,DWORD writecursor,DWORD writebytes,LPVOID lplpaudioptr1,LPDWORD audiobytes1,LPVOID lplpaudioptr2,LPDWORD audiobytes2,DWORD flags
575 ) {
576         ICOM_THIS(PrimaryBufferImpl,iface);
577         IDirectSoundImpl* dsound = This->dsound;
578
579         TRACE("(%p,%ld,%ld,%p,%p,%p,%p,0x%08lx) at %ld\n",
580                 This,
581                 writecursor,
582                 writebytes,
583                 lplpaudioptr1,
584                 audiobytes1,
585                 lplpaudioptr2,
586                 audiobytes2,
587                 flags,
588                 GetTickCount()
589         );
590
591         if (dsound->priolevel != DSSCL_WRITEPRIMARY)
592                 return DSERR_PRIOLEVELNEEDED;
593
594         if (flags & DSBLOCK_FROMWRITECURSOR) {
595                 DWORD writepos;
596                 /* GetCurrentPosition does too much magic to duplicate here */
597                 IDirectSoundBuffer_GetCurrentPosition(iface, NULL, &writepos);
598                 writecursor += writepos;
599         }
600         while (writecursor >= dsound->buflen)
601                 writecursor -= dsound->buflen;
602         if (flags & DSBLOCK_ENTIREBUFFER)
603                 writebytes = dsound->buflen;
604         if (writebytes > dsound->buflen)
605                 writebytes = dsound->buflen;
606
607         assert(audiobytes1!=audiobytes2);
608         assert(lplpaudioptr1!=lplpaudioptr2);
609
610         if (!(dsound->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK) && dsound->hwbuf) {
611                 IDsDriverBuffer_Lock(dsound->hwbuf,
612                                      lplpaudioptr1, audiobytes1,
613                                      lplpaudioptr2, audiobytes2,
614                                      writecursor, writebytes,
615                                      0);
616         }
617         else {
618                 if (writecursor+writebytes <= dsound->buflen) {
619                         *(LPBYTE*)lplpaudioptr1 = dsound->buffer+writecursor;
620                         *audiobytes1 = writebytes;
621                         if (lplpaudioptr2)
622                                 *(LPBYTE*)lplpaudioptr2 = NULL;
623                         if (audiobytes2)
624                                 *audiobytes2 = 0;
625                         TRACE("->%ld.0\n",writebytes);
626                 } else {
627                         *(LPBYTE*)lplpaudioptr1 = dsound->buffer+writecursor;
628                         *audiobytes1 = dsound->buflen-writecursor;
629                         if (lplpaudioptr2)
630                                 *(LPBYTE*)lplpaudioptr2 = dsound->buffer;
631                         if (audiobytes2)
632                                 *audiobytes2 = writebytes-(dsound->buflen-writecursor);
633                         TRACE("->%ld.%ld\n",*audiobytes1,audiobytes2?*audiobytes2:0);
634                 }
635         }
636         return DS_OK;
637 }
638
639 static HRESULT WINAPI PrimaryBufferImpl_SetCurrentPosition(
640         LPDIRECTSOUNDBUFFER8 iface,DWORD newpos
641 ) {
642         ICOM_THIS(PrimaryBufferImpl,iface);
643         TRACE("(%p,%ld)\n",This,newpos);
644
645         /* You cannot set the position of the primary buffer */
646         return DSERR_INVALIDCALL;
647 }
648
649 static HRESULT WINAPI PrimaryBufferImpl_SetPan(
650         LPDIRECTSOUNDBUFFER8 iface,LONG pan
651 ) {
652         ICOM_THIS(PrimaryBufferImpl,iface);
653         TRACE("(%p,%ld)\n",This,pan);
654
655         /* You cannot set the pan of the primary buffer */
656         return DSERR_CONTROLUNAVAIL;
657 }
658
659 static HRESULT WINAPI PrimaryBufferImpl_GetPan(
660         LPDIRECTSOUNDBUFFER8 iface,LPLONG pan
661 ) {
662         ICOM_THIS(PrimaryBufferImpl,iface);
663         TRACE("(%p,%p)\n",This,pan);
664
665         if (pan == NULL)
666                 return DSERR_INVALIDPARAM;
667
668         *pan = This->dsound->volpan.lPan;
669
670         return DS_OK;
671 }
672
673 static HRESULT WINAPI PrimaryBufferImpl_Unlock(
674         LPDIRECTSOUNDBUFFER8 iface,LPVOID p1,DWORD x1,LPVOID p2,DWORD x2
675 ) {
676         ICOM_THIS(PrimaryBufferImpl,iface);
677         IDirectSoundImpl* dsound = This->dsound;
678
679         TRACE("(%p,%p,%ld,%p,%ld):stub\n", This,p1,x1,p2,x2);
680
681         if (dsound->priolevel != DSSCL_WRITEPRIMARY)
682                 return DSERR_PRIOLEVELNEEDED;
683
684         if (!(dsound->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK) && dsound->hwbuf) {
685                 IDsDriverBuffer_Unlock(dsound->hwbuf, p1, x1, p2, x2);
686         }
687
688         return DS_OK;
689 }
690
691 static HRESULT WINAPI PrimaryBufferImpl_Restore(
692         LPDIRECTSOUNDBUFFER8 iface
693 ) {
694         ICOM_THIS(PrimaryBufferImpl,iface);
695         FIXME("(%p):stub\n",This);
696         return DS_OK;
697 }
698
699 static HRESULT WINAPI PrimaryBufferImpl_GetFrequency(
700         LPDIRECTSOUNDBUFFER8 iface,LPDWORD freq
701 ) {
702         ICOM_THIS(PrimaryBufferImpl,iface);
703         TRACE("(%p,%p)\n",This,freq);
704
705         if (freq == NULL)
706                 return DSERR_INVALIDPARAM;
707
708         *freq = This->dsound->wfx.nSamplesPerSec;
709         TRACE("-> %ld\n", *freq);
710
711         return DS_OK;
712 }
713
714 static HRESULT WINAPI PrimaryBufferImpl_SetFX(
715         LPDIRECTSOUNDBUFFER8 iface,DWORD dwEffectsCount,LPDSEFFECTDESC pDSFXDesc,LPDWORD pdwResultCodes
716 ) {
717         ICOM_THIS(PrimaryBufferImpl,iface);
718         DWORD u;
719
720         FIXME("(%p,%lu,%p,%p): stub\n",This,dwEffectsCount,pDSFXDesc,pdwResultCodes);
721
722         if (pdwResultCodes)
723                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
724
725         return DSERR_CONTROLUNAVAIL;
726 }
727
728 static HRESULT WINAPI PrimaryBufferImpl_AcquireResources(
729         LPDIRECTSOUNDBUFFER8 iface,DWORD dwFlags,DWORD dwEffectsCount,LPDWORD pdwResultCodes
730 ) {
731         ICOM_THIS(PrimaryBufferImpl,iface);
732         DWORD u;
733
734         FIXME("(%p,%08lu,%lu,%p): stub\n",This,dwFlags,dwEffectsCount,pdwResultCodes);
735
736         if (pdwResultCodes)
737                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
738
739         return DSERR_CONTROLUNAVAIL;
740 }
741
742 static HRESULT WINAPI PrimaryBufferImpl_GetObjectInPath(
743         LPDIRECTSOUNDBUFFER8 iface,REFGUID rguidObject,DWORD dwIndex,REFGUID rguidInterface,LPVOID* ppObject
744 ) {
745         ICOM_THIS(PrimaryBufferImpl,iface);
746
747         FIXME("(%p,%s,%lu,%s,%p): stub\n",This,debugstr_guid(rguidObject),dwIndex,debugstr_guid(rguidInterface),ppObject);
748
749         return DSERR_CONTROLUNAVAIL;
750 }
751
752 static HRESULT WINAPI PrimaryBufferImpl_Initialize(
753         LPDIRECTSOUNDBUFFER8 iface,LPDIRECTSOUND8 dsound,LPDSBUFFERDESC dbsd
754 ) {
755         ICOM_THIS(PrimaryBufferImpl,iface);
756         FIXME("(%p,%p,%p):stub\n",This,dsound,dbsd);
757         DPRINTF("Re-Init!!!\n");
758         return DSERR_ALREADYINITIALIZED;
759 }
760
761 static HRESULT WINAPI PrimaryBufferImpl_GetCaps(
762         LPDIRECTSOUNDBUFFER8 iface,LPDSBCAPS caps
763 ) {
764         ICOM_THIS(PrimaryBufferImpl,iface);
765         TRACE("(%p)->(%p)\n",This,caps);
766
767         if (caps == NULL || caps->dwSize!=sizeof(*caps))
768                 return DSERR_INVALIDPARAM;
769
770         caps->dwFlags = This->dsbd.dwFlags;
771         if (This->dsound->hwbuf) caps->dwFlags |= DSBCAPS_LOCHARDWARE;
772         else caps->dwFlags |= DSBCAPS_LOCSOFTWARE;
773
774         caps->dwBufferBytes = This->dsound->buflen;
775
776         /* This value represents the speed of the "unlock" command.
777            As unlock is quite fast (it does not do anything), I put
778            4096 ko/s = 4 Mo / s */
779         /* FIXME: hwbuf speed */
780         caps->dwUnlockTransferRate = 4096;
781         caps->dwPlayCpuOverhead = 0;
782
783         return DS_OK;
784 }
785
786 static HRESULT WINAPI PrimaryBufferImpl_QueryInterface(
787         LPDIRECTSOUNDBUFFER8 iface,REFIID riid,LPVOID *ppobj
788 ) {
789         ICOM_THIS(PrimaryBufferImpl,iface);
790
791         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
792
793         if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
794                 ERR("app requested IDirectSoundNotify on primary buffer\n");
795                 /* should we support this? */
796                 *ppobj = NULL;
797                 return E_FAIL;
798         }
799
800         if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
801                 ERR("app requested IDirectSound3DBuffer on primary buffer\n");
802                 *ppobj = NULL;
803                 return E_NOINTERFACE;
804         }
805
806         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
807                 if (!This->dsound->listener)
808                         IDirectSound3DListenerImpl_Create(This, &This->dsound->listener);
809                 *ppobj = This->dsound->listener;
810                 if (This->dsound->listener) {
811                         IDirectSound3DListener_AddRef((LPDIRECTSOUND3DLISTENER)*ppobj);
812                         return DS_OK;
813                 }
814                 return E_FAIL;
815         }
816
817         if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
818 #if 0
819                 if (!This->iks)
820                         IKsPropertySetImpl_Create(This, &This->iks);
821                 *ppobj = This->iks;
822                 if (*ppobj) {
823                         IKsPropertySet_AddRef((LPKSPROPERTYSET)*ppobj);
824                         return S_OK;
825                 }
826                 return E_FAIL;
827 #else
828                 FIXME("app requested IKsPropertySet on primary buffer\n");
829                 *ppobj = NULL;
830                 return E_FAIL;
831 #endif
832         }
833
834         FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
835
836         *ppobj = NULL;
837
838         return E_NOINTERFACE;
839 }
840
841 static ICOM_VTABLE(IDirectSoundBuffer8) dspbvt =
842 {
843         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
844         PrimaryBufferImpl_QueryInterface,
845         PrimaryBufferImpl_AddRef,
846         PrimaryBufferImpl_Release,
847         PrimaryBufferImpl_GetCaps,
848         PrimaryBufferImpl_GetCurrentPosition,
849         PrimaryBufferImpl_GetFormat,
850         PrimaryBufferImpl_GetVolume,
851         PrimaryBufferImpl_GetPan,
852         PrimaryBufferImpl_GetFrequency,
853         PrimaryBufferImpl_GetStatus,
854         PrimaryBufferImpl_Initialize,
855         PrimaryBufferImpl_Lock,
856         PrimaryBufferImpl_Play,
857         PrimaryBufferImpl_SetCurrentPosition,
858         PrimaryBufferImpl_SetFormat,
859         PrimaryBufferImpl_SetVolume,
860         PrimaryBufferImpl_SetPan,
861         PrimaryBufferImpl_SetFrequency,
862         PrimaryBufferImpl_Stop,
863         PrimaryBufferImpl_Unlock,
864         PrimaryBufferImpl_Restore,
865         PrimaryBufferImpl_SetFX,
866         PrimaryBufferImpl_AcquireResources,
867         PrimaryBufferImpl_GetObjectInPath
868 };
869
870 HRESULT WINAPI PrimaryBuffer_Create(
871         IDirectSoundImpl *This,
872         PrimaryBufferImpl **pdsb,
873         LPDSBUFFERDESC dsbd)
874 {
875         PrimaryBufferImpl *dsb;
876
877         if (dsbd->lpwfxFormat)
878                 return DSERR_INVALIDPARAM;
879
880         dsb = (PrimaryBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*dsb));
881         dsb->ref = 1;
882         dsb->dsound = This;
883         dsb->lpVtbl = &dspbvt;
884
885         memcpy(&dsb->dsbd, dsbd, sizeof(*dsbd));
886
887         TRACE("Created primary buffer at %p\n", dsb);
888
889         if (dsbd->dwFlags & DSBCAPS_CTRL3D) {
890                 /* FIXME: IDirectSound3DListener */
891         }
892
893         IDirectSound8_AddRef((LPDIRECTSOUND8)This);
894
895         *pdsb = dsb;
896         return S_OK;
897 }