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