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