Implement A_SHA* functions present in Windows XP and later systems.
[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 <stdarg.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <sys/fcntl.h>
28 #ifdef HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif
31 #include <stdlib.h>
32 #include <string.h>
33 #include <math.h>       /* Insomnia - pow() function */
34
35 #include "windef.h"
36 #include "winbase.h"
37 #include "wingdi.h"
38 #include "winuser.h"
39 #include "winerror.h"
40 #include "mmsystem.h"
41 #include "winreg.h"
42 #include "winternl.h"
43 #include "mmddk.h"
44 #include "wine/windef16.h"
45 #include "wine/debug.h"
46 #include "dsound.h"
47 #include "dsdriver.h"
48 #include "dsound_private.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
51
52 void DSOUND_RecalcPrimary(IDirectSoundImpl *This)
53 {
54         DWORD sw;
55         TRACE("(%p)\n",This);
56
57         sw = This->pwfx->nChannels * (This->pwfx->wBitsPerSample / 8);
58         if (This->hwbuf) {
59                 DWORD fraglen;
60                 /* let fragment size approximate the timer delay */
61                 fraglen = (This->pwfx->nSamplesPerSec * DS_TIME_DEL / 1000) * sw;
62                 /* reduce fragment size until an integer number of them fits in the buffer */
63                 /* (FIXME: this may or may not be a good idea) */
64                 while (This->buflen % fraglen) fraglen -= sw;
65                 This->fraglen = fraglen;
66                 TRACE("fraglen=%ld\n", This->fraglen);
67         }
68         /* calculate the 10ms write lead */
69         This->writelead = (This->pwfx->nSamplesPerSec / 100) * sw;
70 }
71
72 static HRESULT DSOUND_PrimaryOpen(IDirectSoundImpl *This)
73 {
74         HRESULT err = DS_OK;
75         TRACE("(%p)\n",This);
76
77         /* are we using waveOut stuff? */
78         if (!This->driver) {
79                 LPBYTE newbuf;
80                 DWORD buflen;
81                 HRESULT merr = DS_OK;
82                 /* Start in pause mode, to allow buffers to get filled */
83                 waveOutPause(This->hwo);
84                 if (This->state == STATE_PLAYING) This->state = STATE_STARTING;
85                 else if (This->state == STATE_STOPPING) This->state = STATE_STOPPED;
86                 /* use fragments of 10ms (1/100s) each (which should get us within
87                  * the documented write cursor lead of 10-15ms) */
88                 buflen = ((This->pwfx->nAvgBytesPerSec / 100) & ~3) * DS_HEL_FRAGS;
89                 TRACE("desired buflen=%ld, old buffer=%p\n", buflen, This->buffer);
90                 /* reallocate emulated primary buffer */
91
92                 if (This->buffer)
93                         newbuf = HeapReAlloc(GetProcessHeap(),0,This->buffer,buflen);
94                 else
95                         newbuf = HeapAlloc(GetProcessHeap(),0,buflen);
96
97                 if (newbuf == NULL) {
98                         ERR("failed to allocate primary buffer\n");
99                         merr = DSERR_OUTOFMEMORY;
100                         /* but the old buffer might still exist and must be re-prepared */
101                 } else {
102                         This->buffer = newbuf;
103                         This->buflen = buflen;
104                 }
105                 if (This->buffer) {
106                         unsigned c;
107
108                         This->fraglen = This->buflen / DS_HEL_FRAGS;
109
110                         /* prepare fragment headers */
111                         for (c=0; c<DS_HEL_FRAGS; c++) {
112                                 This->pwave[c]->lpData = This->buffer + c*This->fraglen;
113                                 This->pwave[c]->dwBufferLength = This->fraglen;
114                                 This->pwave[c]->dwUser = (DWORD)This;
115                                 This->pwave[c]->dwFlags = 0;
116                                 This->pwave[c]->dwLoops = 0;
117                                 err = mmErr(waveOutPrepareHeader(This->hwo,This->pwave[c],sizeof(WAVEHDR)));
118                                 if (err != DS_OK) {
119                                         while (c--)
120                                                 waveOutUnprepareHeader(This->hwo,This->pwave[c],sizeof(WAVEHDR));
121                                         break;
122                                 }
123                         }
124
125                         This->pwplay = 0;
126                         This->pwwrite = 0;
127                         This->pwqueue = 0;
128                         This->playpos = 0;
129                         This->mixpos = 0;
130                         memset(This->buffer, (This->pwfx->wBitsPerSample == 16) ? 0 : 128, This->buflen);
131                         TRACE("fraglen=%ld\n", This->fraglen);
132                         DSOUND_WaveQueue(This, (DWORD)-1);
133                 }
134                 if ((err == DS_OK) && (merr != DS_OK))
135                         err = merr;
136         } else if (!This->hwbuf) {
137                 err = IDsDriver_CreateSoundBuffer(This->driver,This->pwfx,
138                                                   DSBCAPS_PRIMARYBUFFER,0,
139                                                   &(This->buflen),&(This->buffer),
140                                                   (LPVOID*)&(This->hwbuf));
141                 if (err != DS_OK) {
142                         WARN("IDsDriver_CreateSoundBuffer failed\n");
143                         return err;
144                 }
145
146                 if (dsound->state == STATE_PLAYING) dsound->state = STATE_STARTING;
147                 else if (dsound->state == STATE_STOPPING) dsound->state = STATE_STOPPED;
148         }
149
150         return err;
151 }
152
153
154 static void DSOUND_PrimaryClose(IDirectSoundImpl *This)
155 {
156         TRACE("(%p)\n",This);
157
158         /* are we using waveOut stuff? */
159         if (!This->hwbuf) {
160                 unsigned c;
161
162                 This->pwqueue = (DWORD)-1; /* resetting queues */
163                 waveOutReset(This->hwo);
164                 for (c=0; c<DS_HEL_FRAGS; c++)
165                         waveOutUnprepareHeader(This->hwo, This->pwave[c], sizeof(WAVEHDR));
166                 This->pwqueue = 0;
167         } else {
168                 if (IDsDriverBuffer_Release(This->hwbuf) == 0)
169                         This->hwbuf = 0;
170         }
171 }
172
173 HRESULT DSOUND_PrimaryCreate(IDirectSoundImpl *This)
174 {
175         HRESULT err = DS_OK;
176         TRACE("(%p)\n",This);
177
178         This->buflen = This->pwfx->nAvgBytesPerSec;
179
180         /* FIXME: verify that hardware capabilities (DSCAPS_PRIMARY flags) match */
181
182         if (This->driver) {
183                 err = IDsDriver_CreateSoundBuffer(This->driver,This->pwfx,
184                                                   DSBCAPS_PRIMARYBUFFER,0,
185                                                   &(This->buflen),&(This->buffer),
186                                                   (LPVOID*)&(This->hwbuf));
187                 if (err != DS_OK) {
188                         WARN("IDsDriver_CreateSoundBuffer failed\n");
189                         return err;
190                 }
191         }
192         if (!This->hwbuf) {
193                 /* Allocate memory for HEL buffer headers */
194                 unsigned c;
195                 for (c=0; c<DS_HEL_FRAGS; c++) {
196                         This->pwave[c] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(WAVEHDR));
197                         if (!This->pwave[c]) {
198                                 /* Argh, out of memory */
199                                 while (c--) {
200                                         HeapFree(GetProcessHeap(),0,This->pwave[c]);
201                                 }
202                                 WARN("out of memory\n");
203                                 return DSERR_OUTOFMEMORY;
204                         }
205                 }
206         }
207
208         err = DSOUND_PrimaryOpen(This);
209
210         if (err != DS_OK) {
211                 WARN("DSOUND_PrimaryOpen failed\n");
212                 return err;
213         }
214
215         /* calculate fragment size and write lead */
216         DSOUND_RecalcPrimary(This);
217         This->state = STATE_STOPPED;
218         return DS_OK;
219 }
220
221 HRESULT DSOUND_PrimaryDestroy(IDirectSoundImpl *This)
222 {
223         TRACE("(%p)\n",This);
224
225         DSOUND_PrimaryClose(This);
226         if (This->driver) {
227                 if (This->hwbuf) {
228                         if (IDsDriverBuffer_Release(This->hwbuf) == 0)
229                                 This->hwbuf = 0;
230                 }
231         } else {
232                 unsigned c;
233                 for (c=0; c<DS_HEL_FRAGS; c++) {
234                         HeapFree(GetProcessHeap(),0,This->pwave[c]);
235                 }
236         }
237         if (This->pwfx) {
238                 HeapFree(GetProcessHeap(),0,This->pwfx);
239                 This->pwfx=NULL;
240         }
241         return DS_OK;
242 }
243
244 HRESULT DSOUND_PrimaryPlay(IDirectSoundImpl *This)
245 {
246         HRESULT err = DS_OK;
247         TRACE("(%p)\n",This);
248
249         if (This->hwbuf) {
250                 err = IDsDriverBuffer_Play(This->hwbuf, 0, 0, DSBPLAY_LOOPING);
251                 if (err != DS_OK)
252                         WARN("IDsDriverBuffer_Play failed\n");
253         } else {
254                 err = mmErr(waveOutRestart(This->hwo));
255                 if (err != DS_OK)
256                         WARN("waveOutRestart failed\n");
257         }
258
259         return err;
260 }
261
262 HRESULT DSOUND_PrimaryStop(IDirectSoundImpl *This)
263 {
264         HRESULT err = DS_OK;
265         TRACE("(%p)\n",This);
266
267         if (This->hwbuf) {
268                 err = IDsDriverBuffer_Stop(This->hwbuf);
269                 if (err == DSERR_BUFFERLOST) {
270                         DWORD flags = CALLBACK_FUNCTION;
271                         if (ds_hw_accel != DS_HW_ACCEL_EMULATION)
272                                 flags |= WAVE_DIRECTSOUND;
273                         /* Wine-only: the driver wants us to reopen the device */
274                         /* FIXME: check for errors */
275                         IDsDriverBuffer_Release(This->hwbuf);
276                         waveOutClose(This->hwo);
277                         This->hwo = 0;
278                         err = mmErr(waveOutOpen(&(This->hwo), This->drvdesc.dnDevNode,
279                                                 This->pwfx, (DWORD)DSOUND_callback, (DWORD)This,
280                                                 flags));
281                         if (err == DS_OK) {
282                                 err = IDsDriver_CreateSoundBuffer(This->driver,This->pwfx,
283                                                                   DSBCAPS_PRIMARYBUFFER,0,
284                                                                   &(This->buflen),&(This->buffer),
285                                                                   (LPVOID)&(This->hwbuf));
286                                 if (err != DS_OK)
287                                         WARN("IDsDriver_CreateSoundBuffer failed\n");
288                         } else {
289                                 WARN("waveOutOpen failed\n");
290                         }
291                 } else if (err != DS_OK) {
292                         WARN("IDsDriverBuffer_Stop failed\n");
293                 }
294         } else {
295                 err = mmErr(waveOutPause(This->hwo));
296                 if (err != DS_OK)
297                         WARN("waveOutPause failed\n");
298         }
299         return err;
300 }
301
302 HRESULT DSOUND_PrimaryGetPosition(IDirectSoundImpl *This, LPDWORD playpos, LPDWORD writepos)
303 {
304         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
305
306         if (This->hwbuf) {
307                 HRESULT err=IDsDriverBuffer_GetPosition(This->hwbuf,playpos,writepos);
308                 if (err) {
309                         WARN("IDsDriverBuffer_GetPosition failed\n");
310                         return err;
311                 }
312         } else {
313                 if (playpos) {
314                         MMTIME mtime;
315                         mtime.wType = TIME_BYTES;
316                         waveOutGetPosition(This->hwo, &mtime, sizeof(mtime));
317                         mtime.u.cb = mtime.u.cb % This->buflen;
318                         *playpos = mtime.u.cb;
319                 }
320                 if (writepos) {
321                         /* the writepos should only be used by apps with WRITEPRIMARY priority,
322                          * in which case our software mixer is disabled anyway */
323                         *writepos = (This->pwplay + ds_hel_margin) * This->fraglen;
324                         while (*writepos >= This->buflen)
325                                 *writepos -= This->buflen;
326                 }
327         }
328         TRACE("playpos = %ld, writepos = %ld (%p, time=%ld)\n", playpos?*playpos:0, writepos?*writepos:0, This, GetTickCount());
329         return DS_OK;
330 }
331
332 /*******************************************************************************
333  *              PrimaryBuffer
334  */
335 /* This sets this format for the <em>Primary Buffer Only</em> */
336 /* See file:///cdrom/sdk52/docs/worddoc/dsound.doc page 120 */
337 static HRESULT WINAPI PrimaryBufferImpl_SetFormat(
338         LPDIRECTSOUNDBUFFER8 iface,LPCWAVEFORMATEX wfex
339 ) {
340         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
341         IDirectSoundImpl* dsound = This->dsound;
342         HRESULT err = DS_OK;
343         int i, alloc_size, cp_size;
344         DWORD nSamplesPerSec;
345         TRACE("(%p,%p)\n",This,wfex);
346
347         if (This->dsound->priolevel == DSSCL_NORMAL) {
348                 WARN("failed priority check!\n");
349                 return DSERR_PRIOLEVELNEEDED;
350         }
351
352         /* Let's be pedantic! */
353         if (wfex == NULL) {
354                 WARN("invalid parameter: wfex==NULL!\n");
355                 return DSERR_INVALIDPARAM;
356         }
357         TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld,"
358               "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
359               wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
360               wfex->nAvgBytesPerSec, wfex->nBlockAlign,
361               wfex->wBitsPerSample, wfex->cbSize);
362
363         /* **** */
364         RtlAcquireResourceExclusive(&(dsound->buffer_list_lock), TRUE);
365
366         if (wfex->wFormatTag == WAVE_FORMAT_PCM) {
367             alloc_size = sizeof(WAVEFORMATEX);
368             cp_size = sizeof(PCMWAVEFORMAT);
369         } else
370             alloc_size = cp_size = sizeof(WAVEFORMATEX) + wfex->cbSize;
371
372         dsound->pwfx = HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,dsound->pwfx,alloc_size);
373
374         nSamplesPerSec = dsound->pwfx->nSamplesPerSec;
375
376         memcpy(dsound->pwfx, wfex, cp_size);
377
378         if (dsound->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMSETFORMAT) {
379                 DWORD flags = CALLBACK_FUNCTION;
380                 if (ds_hw_accel != DS_HW_ACCEL_EMULATION)
381                         flags |= WAVE_DIRECTSOUND;
382                 /* FIXME: check for errors */
383                 DSOUND_PrimaryClose(dsound);
384                 waveOutClose(dsound->hwo);
385                 dsound->hwo = 0;
386                 err = mmErr(waveOutOpen(&(dsound->hwo), dsound->drvdesc.dnDevNode,
387                                         dsound->pwfx, (DWORD)DSOUND_callback, (DWORD)dsound,
388                                         flags));
389                 if (err == DS_OK) {
390                     err = DSOUND_PrimaryOpen(dsound);
391                     if (err != DS_OK) {
392                             WARN("DSOUND_PrimaryOpen failed\n");
393                             RtlReleaseResource(&(dsound->buffer_list_lock));
394                             return err;
395                     }
396                 } else {
397                         WARN("waveOutOpen failed\n");
398                         RtlReleaseResource(&(dsound->buffer_list_lock));
399                         return err;
400                 }
401         } else if (dsound->hwbuf) {
402                 err = IDsDriverBuffer_SetFormat(dsound->hwbuf, dsound->pwfx);
403                 if (err == DSERR_BUFFERLOST) {
404                         /* Wine-only: the driver wants us to recreate the HW buffer */
405                         IDsDriverBuffer_Release(dsound->hwbuf);
406                         err = IDsDriver_CreateSoundBuffer(dsound->driver,dsound->pwfx,
407                                                           DSBCAPS_PRIMARYBUFFER,0,
408                                                           &(dsound->buflen),&(dsound->buffer),
409                                                           (LPVOID)&(dsound->hwbuf));
410                         if (err != DS_OK) {
411                                 WARN("IDsDriver_CreateSoundBuffer failed\n");
412                                 RtlReleaseResource(&(dsound->buffer_list_lock));
413                                 return err;
414                         }
415                         if (dsound->state == STATE_PLAYING) dsound->state = STATE_STARTING;
416                         else if (dsound->state == STATE_STOPPING) dsound->state = STATE_STOPPED;
417                 } else {
418                         WARN("IDsDriverBuffer_SetFormat failed\n");
419                         RtlReleaseResource(&(dsound->buffer_list_lock));
420                         return err;
421                 }
422                 /* FIXME: should we set err back to DS_OK in all cases ? */
423         }
424         DSOUND_RecalcPrimary(dsound);
425
426         if (nSamplesPerSec != dsound->pwfx->nSamplesPerSec) {
427                 IDirectSoundBufferImpl** dsb = dsound->buffers;
428                 for (i = 0; i < dsound->nrofbuffers; i++, dsb++) {
429                         /* **** */
430                         EnterCriticalSection(&((*dsb)->lock));
431
432                         (*dsb)->freqAdjust = ((*dsb)->freq << DSOUND_FREQSHIFT) /
433                                 wfex->nSamplesPerSec;
434
435                         LeaveCriticalSection(&((*dsb)->lock));
436                         /* **** */
437                 }
438         }
439
440         RtlReleaseResource(&(dsound->buffer_list_lock));
441         /* **** */
442
443         return err;
444 }
445
446 static HRESULT WINAPI PrimaryBufferImpl_SetVolume(
447         LPDIRECTSOUNDBUFFER8 iface,LONG vol
448 ) {
449         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
450         IDirectSoundImpl* dsound = This->dsound;
451         DWORD ampfactors;
452         DSVOLUMEPAN volpan;
453         HRESULT hres = DS_OK;
454
455         TRACE("(%p,%ld)\n",This,vol);
456
457         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
458                 WARN("control unavailable\n");
459                 return DSERR_CONTROLUNAVAIL;
460         }
461
462         if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN)) {
463                 WARN("invalid parameter: vol = %ld\n", vol);
464                 return DSERR_INVALIDPARAM;
465         }
466
467         /* **** */
468         EnterCriticalSection(&(dsound->mixlock));
469
470         waveOutGetVolume(dsound->hwo, &ampfactors);
471         volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
472         volpan.dwTotalRightAmpFactor=ampfactors >> 16;
473         DSOUND_AmpFactorToVolPan(&volpan);
474         if (vol != volpan.lVolume) {
475             volpan.lVolume=vol;
476             DSOUND_RecalcVolPan(&volpan);
477             if (dsound->hwbuf) {
478                 hres = IDsDriverBuffer_SetVolumePan(dsound->hwbuf, &volpan);
479                 if (hres != DS_OK)
480                     WARN("IDsDriverBuffer_SetVolumePan failed\n");
481             } else {
482                 ampfactors = (volpan.dwTotalLeftAmpFactor & 0xffff) | (volpan.dwTotalRightAmpFactor << 16);
483                 waveOutSetVolume(dsound->hwo, ampfactors);
484             }
485         }
486
487         LeaveCriticalSection(&(dsound->mixlock));
488         /* **** */
489
490         return hres;
491 }
492
493 static HRESULT WINAPI PrimaryBufferImpl_GetVolume(
494         LPDIRECTSOUNDBUFFER8 iface,LPLONG vol
495 ) {
496         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
497         DWORD ampfactors;
498         DSVOLUMEPAN volpan;
499         TRACE("(%p,%p)\n",This,vol);
500
501         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
502                 WARN("control unavailable\n");
503                 return DSERR_CONTROLUNAVAIL;
504         }
505
506         if (vol == NULL) {
507                 WARN("invalid parameter: vol = NULL\n");
508                 return DSERR_INVALIDPARAM;
509         }
510
511         waveOutGetVolume(dsound->hwo, &ampfactors);
512         volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
513         volpan.dwTotalRightAmpFactor=ampfactors >> 16;
514         DSOUND_AmpFactorToVolPan(&volpan);
515         *vol = volpan.lVolume;
516         return DS_OK;
517 }
518
519 static HRESULT WINAPI PrimaryBufferImpl_SetFrequency(
520         LPDIRECTSOUNDBUFFER8 iface,DWORD freq
521 ) {
522         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
523
524         TRACE("(%p,%ld)\n",This,freq);
525
526         /* You cannot set the frequency of the primary buffer */
527         WARN("control unavailable\n");
528         return DSERR_CONTROLUNAVAIL;
529 }
530
531 static HRESULT WINAPI PrimaryBufferImpl_Play(
532         LPDIRECTSOUNDBUFFER8 iface,DWORD reserved1,DWORD reserved2,DWORD flags
533 ) {
534         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
535         IDirectSoundImpl* dsound = This->dsound;
536
537         TRACE("(%p,%08lx,%08lx,%08lx)\n",
538                 This,reserved1,reserved2,flags
539         );
540
541         if (!(flags & DSBPLAY_LOOPING)) {
542                 WARN("invalid parameter: flags = %08lx\n", flags);
543                 return DSERR_INVALIDPARAM;
544         }
545
546         /* **** */
547         EnterCriticalSection(&(dsound->mixlock));
548
549         if (dsound->state == STATE_STOPPED)
550                 dsound->state = STATE_STARTING;
551         else if (dsound->state == STATE_STOPPING)
552                 dsound->state = STATE_PLAYING;
553
554         LeaveCriticalSection(&(dsound->mixlock));
555         /* **** */
556
557         return DS_OK;
558 }
559
560 static HRESULT WINAPI PrimaryBufferImpl_Stop(LPDIRECTSOUNDBUFFER8 iface)
561 {
562         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
563         IDirectSoundImpl* dsound = This->dsound;
564
565         TRACE("(%p)\n",This);
566
567         /* **** */
568         EnterCriticalSection(&(dsound->mixlock));
569
570         if (dsound->state == STATE_PLAYING)
571                 dsound->state = STATE_STOPPING;
572         else if (dsound->state == STATE_STARTING)
573                 dsound->state = STATE_STOPPED;
574
575         LeaveCriticalSection(&(dsound->mixlock));
576         /* **** */
577
578         return DS_OK;
579 }
580
581 static ULONG WINAPI PrimaryBufferImpl_AddRef(LPDIRECTSOUNDBUFFER8 iface) {
582         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
583         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
584         return InterlockedIncrement(&(This->ref));
585 }
586
587 static ULONG WINAPI PrimaryBufferImpl_Release(LPDIRECTSOUNDBUFFER8 iface) {
588         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
589         DWORD ref;
590
591         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
592         ref = InterlockedDecrement(&(This->ref));
593
594         if (ref == 0) {
595                 This->dsound->primary = NULL;
596                 HeapFree(GetProcessHeap(),0,This);
597                 TRACE("(%p) released\n",This);
598         }
599
600         return ref;
601 }
602
603 static HRESULT WINAPI PrimaryBufferImpl_GetCurrentPosition(
604         LPDIRECTSOUNDBUFFER8 iface,LPDWORD playpos,LPDWORD writepos
605 ) {
606         HRESULT hres;
607         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
608         IDirectSoundImpl* dsound = This->dsound;
609
610         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
611         hres = DSOUND_PrimaryGetPosition(dsound, playpos, writepos);
612         if (hres != DS_OK) {
613                 WARN("DSOUND_PrimaryGetPosition failed\n");
614                 return hres;
615         }
616         if (writepos) {
617                 if (dsound->state != STATE_STOPPED)
618                         /* apply the documented 10ms lead to writepos */
619                         *writepos += dsound->writelead;
620                 while (*writepos >= dsound->buflen) *writepos -= dsound->buflen;
621         }
622         TRACE("playpos = %ld, writepos = %ld (%p, time=%ld)\n", playpos?*playpos:0, writepos?*writepos:0, This, GetTickCount());
623         return DS_OK;
624 }
625
626 static HRESULT WINAPI PrimaryBufferImpl_GetStatus(
627         LPDIRECTSOUNDBUFFER8 iface,LPDWORD status
628 ) {
629         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
630         TRACE("(%p,%p), thread is %04lx\n",This,status,GetCurrentThreadId());
631
632         if (status == NULL) {
633                 WARN("invalid parameter: status == NULL\n");
634                 return DSERR_INVALIDPARAM;
635         }
636
637         *status = 0;
638         if ((This->dsound->state == STATE_STARTING) ||
639             (This->dsound->state == STATE_PLAYING))
640                 *status |= DSBSTATUS_PLAYING | DSBSTATUS_LOOPING;
641
642         TRACE("status=%lx\n", *status);
643         return DS_OK;
644 }
645
646
647 static HRESULT WINAPI PrimaryBufferImpl_GetFormat(
648     LPDIRECTSOUNDBUFFER8 iface,
649     LPWAVEFORMATEX lpwf,
650     DWORD wfsize,
651     LPDWORD wfwritten)
652 {
653     DWORD size;
654     PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
655     TRACE("(%p,%p,%ld,%p)\n",This,lpwf,wfsize,wfwritten);
656
657     size = sizeof(WAVEFORMATEX) + This->dsound->pwfx->cbSize;
658
659     if (lpwf) { /* NULL is valid */
660         if (wfsize >= size) {
661             memcpy(lpwf,This->dsound->pwfx,size);
662             if (wfwritten)
663                 *wfwritten = size;
664         } else {
665             WARN("invalid parameter: wfsize to small\n");
666             if (wfwritten)
667                 *wfwritten = 0;
668             return DSERR_INVALIDPARAM;
669         }
670     } else {
671         if (wfwritten)
672             *wfwritten = sizeof(WAVEFORMATEX) + This->dsound->pwfx->cbSize;
673         else {
674             WARN("invalid parameter: wfwritten == NULL\n");
675             return DSERR_INVALIDPARAM;
676         }
677     }
678
679     return DS_OK;
680 }
681
682 static HRESULT WINAPI PrimaryBufferImpl_Lock(
683         LPDIRECTSOUNDBUFFER8 iface,DWORD writecursor,DWORD writebytes,LPVOID lplpaudioptr1,LPDWORD audiobytes1,LPVOID lplpaudioptr2,LPDWORD audiobytes2,DWORD flags
684 ) {
685         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
686         IDirectSoundImpl* dsound = This->dsound;
687
688         TRACE("(%p,%ld,%ld,%p,%p,%p,%p,0x%08lx) at %ld\n",
689                 This,
690                 writecursor,
691                 writebytes,
692                 lplpaudioptr1,
693                 audiobytes1,
694                 lplpaudioptr2,
695                 audiobytes2,
696                 flags,
697                 GetTickCount()
698         );
699
700         if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
701                 WARN("failed priority check!\n");
702                 return DSERR_PRIOLEVELNEEDED;
703         }
704
705         if (flags & DSBLOCK_FROMWRITECURSOR) {
706                 DWORD writepos;
707                 HRESULT hres;
708                 /* GetCurrentPosition does too much magic to duplicate here */
709                 hres = IDirectSoundBuffer_GetCurrentPosition(iface, NULL, &writepos);
710                 if (hres != DS_OK) {
711                         WARN("IDirectSoundBuffer_GetCurrentPosition failed\n");
712                         return hres;
713                 }
714                 writecursor += writepos;
715         }
716         while (writecursor >= dsound->buflen)
717                 writecursor -= dsound->buflen;
718         if (flags & DSBLOCK_ENTIREBUFFER)
719                 writebytes = dsound->buflen;
720         if (writebytes > dsound->buflen)
721                 writebytes = dsound->buflen;
722
723         if (!(dsound->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK) && dsound->hwbuf) {
724                 HRESULT hres;
725                 hres = IDsDriverBuffer_Lock(dsound->hwbuf,
726                                             lplpaudioptr1, audiobytes1,
727                                             lplpaudioptr2, audiobytes2,
728                                             writecursor, writebytes,
729                                             0);
730                 if (hres != DS_OK) {
731                         WARN("IDsDriverBuffer_Lock failed\n");
732                         return hres;
733                 }
734         } else {
735                 if (writecursor+writebytes <= dsound->buflen) {
736                         *(LPBYTE*)lplpaudioptr1 = dsound->buffer+writecursor;
737                         *audiobytes1 = writebytes;
738                         if (lplpaudioptr2)
739                                 *(LPBYTE*)lplpaudioptr2 = NULL;
740                         if (audiobytes2)
741                                 *audiobytes2 = 0;
742                         TRACE("->%ld.0\n",writebytes);
743                 } else {
744                         *(LPBYTE*)lplpaudioptr1 = dsound->buffer+writecursor;
745                         *audiobytes1 = dsound->buflen-writecursor;
746                         if (lplpaudioptr2)
747                                 *(LPBYTE*)lplpaudioptr2 = dsound->buffer;
748                         if (audiobytes2)
749                                 *audiobytes2 = writebytes-(dsound->buflen-writecursor);
750                         TRACE("->%ld.%ld\n",*audiobytes1,audiobytes2?*audiobytes2:0);
751                 }
752         }
753         return DS_OK;
754 }
755
756 static HRESULT WINAPI PrimaryBufferImpl_SetCurrentPosition(
757         LPDIRECTSOUNDBUFFER8 iface,DWORD newpos
758 ) {
759         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
760         TRACE("(%p,%ld)\n",This,newpos);
761
762         /* You cannot set the position of the primary buffer */
763         WARN("invalid call\n");
764         return DSERR_INVALIDCALL;
765 }
766
767 static HRESULT WINAPI PrimaryBufferImpl_SetPan(
768         LPDIRECTSOUNDBUFFER8 iface,LONG pan
769 ) {
770         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
771         IDirectSoundImpl* dsound = This->dsound;
772         DWORD ampfactors;
773         DSVOLUMEPAN volpan;
774         HRESULT hres = DS_OK;
775
776         TRACE("(%p,%ld)\n",This,pan);
777
778         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
779                 WARN("control unavailable\n");
780                 return DSERR_CONTROLUNAVAIL;
781         }
782
783         if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT)) {
784                 WARN("invalid parameter: pan = %ld\n", pan);
785                 return DSERR_INVALIDPARAM;
786         }
787
788         /* **** */
789         EnterCriticalSection(&(dsound->mixlock));
790
791         waveOutGetVolume(dsound->hwo, &ampfactors);
792         volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
793         volpan.dwTotalRightAmpFactor=ampfactors >> 16;
794         DSOUND_AmpFactorToVolPan(&volpan);
795         if (pan != volpan.lPan) {
796             volpan.lPan=pan;
797             DSOUND_RecalcVolPan(&volpan);
798             if (dsound->hwbuf) {
799                 hres = IDsDriverBuffer_SetVolumePan(dsound->hwbuf, &volpan);
800                 if (hres != DS_OK)
801                     WARN("IDsDriverBuffer_SetVolumePan failed\n");
802             } else {
803                 ampfactors = (volpan.dwTotalLeftAmpFactor & 0xffff) | (volpan.dwTotalRightAmpFactor << 16);
804                 waveOutSetVolume(dsound->hwo, ampfactors);
805             }
806         }
807
808         LeaveCriticalSection(&(dsound->mixlock));
809         /* **** */
810
811         return hres;
812 }
813
814 static HRESULT WINAPI PrimaryBufferImpl_GetPan(
815         LPDIRECTSOUNDBUFFER8 iface,LPLONG pan
816 ) {
817         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
818         DWORD ampfactors;
819         DSVOLUMEPAN volpan;
820         TRACE("(%p,%p)\n",This,pan);
821
822         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
823                 WARN("control unavailable\n");
824                 return DSERR_CONTROLUNAVAIL;
825         }
826
827         if (pan == NULL) {
828                 WARN("invalid parameter: pan == NULL\n");
829                 return DSERR_INVALIDPARAM;
830         }
831
832         waveOutGetVolume(dsound->hwo, &ampfactors);
833         volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
834         volpan.dwTotalRightAmpFactor=ampfactors >> 16;
835         DSOUND_AmpFactorToVolPan(&volpan);
836         *pan = volpan.lPan;
837         return DS_OK;
838 }
839
840 static HRESULT WINAPI PrimaryBufferImpl_Unlock(
841         LPDIRECTSOUNDBUFFER8 iface,LPVOID p1,DWORD x1,LPVOID p2,DWORD x2
842 ) {
843         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
844         IDirectSoundImpl* dsound = This->dsound;
845
846         TRACE("(%p,%p,%ld,%p,%ld)\n", This,p1,x1,p2,x2);
847
848         if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
849                 WARN("failed priority check!\n");
850                 return DSERR_PRIOLEVELNEEDED;
851         }
852
853         if (!(dsound->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK) && dsound->hwbuf) {
854                 HRESULT hres;
855                 
856                 hres = IDsDriverBuffer_Unlock(dsound->hwbuf, p1, x1, p2, x2);
857                 if (hres != DS_OK) {
858                         WARN("IDsDriverBuffer_Unlock failed\n");
859                         return hres;
860                 }
861         }
862
863         return DS_OK;
864 }
865
866 static HRESULT WINAPI PrimaryBufferImpl_Restore(
867         LPDIRECTSOUNDBUFFER8 iface
868 ) {
869         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
870         FIXME("(%p):stub\n",This);
871         return DS_OK;
872 }
873
874 static HRESULT WINAPI PrimaryBufferImpl_GetFrequency(
875         LPDIRECTSOUNDBUFFER8 iface,LPDWORD freq
876 ) {
877         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
878         TRACE("(%p,%p)\n",This,freq);
879
880         if (freq == NULL) {
881                 WARN("invalid parameter: freq == NULL\n");
882                 return DSERR_INVALIDPARAM;
883         }
884
885         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) {
886                 WARN("control unavailable\n");
887                 return DSERR_CONTROLUNAVAIL;
888         }
889
890         *freq = This->dsound->pwfx->nSamplesPerSec;
891         TRACE("-> %ld\n", *freq);
892
893         return DS_OK;
894 }
895
896 static HRESULT WINAPI PrimaryBufferImpl_SetFX(
897         LPDIRECTSOUNDBUFFER8 iface,DWORD dwEffectsCount,LPDSEFFECTDESC pDSFXDesc,LPDWORD pdwResultCodes
898 ) {
899         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
900         DWORD u;
901
902         FIXME("(%p,%lu,%p,%p): stub\n",This,dwEffectsCount,pDSFXDesc,pdwResultCodes);
903
904         if (pdwResultCodes)
905                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
906
907         WARN("control unavailable\n");
908         return DSERR_CONTROLUNAVAIL;
909 }
910
911 static HRESULT WINAPI PrimaryBufferImpl_AcquireResources(
912         LPDIRECTSOUNDBUFFER8 iface,DWORD dwFlags,DWORD dwEffectsCount,LPDWORD pdwResultCodes
913 ) {
914         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
915         DWORD u;
916
917         FIXME("(%p,%08lu,%lu,%p): stub\n",This,dwFlags,dwEffectsCount,pdwResultCodes);
918
919         if (pdwResultCodes)
920                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
921
922         WARN("control unavailable\n");
923         return DSERR_CONTROLUNAVAIL;
924 }
925
926 static HRESULT WINAPI PrimaryBufferImpl_GetObjectInPath(
927         LPDIRECTSOUNDBUFFER8 iface,REFGUID rguidObject,DWORD dwIndex,REFGUID rguidInterface,LPVOID* ppObject
928 ) {
929         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
930
931         FIXME("(%p,%s,%lu,%s,%p): stub\n",This,debugstr_guid(rguidObject),dwIndex,debugstr_guid(rguidInterface),ppObject);
932
933         WARN("control unavailable\n");
934         return DSERR_CONTROLUNAVAIL;
935 }
936
937 static HRESULT WINAPI PrimaryBufferImpl_Initialize(
938         LPDIRECTSOUNDBUFFER8 iface,LPDIRECTSOUND dsound,LPCDSBUFFERDESC dbsd
939 ) {
940         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
941         FIXME("(%p,%p,%p):stub\n",This,dsound,dbsd);
942         DPRINTF("Re-Init!!!\n");
943         WARN("already initialized\n");
944         return DSERR_ALREADYINITIALIZED;
945 }
946
947 static HRESULT WINAPI PrimaryBufferImpl_GetCaps(
948         LPDIRECTSOUNDBUFFER8 iface,LPDSBCAPS caps
949 ) {
950         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
951         TRACE("(%p)->(%p)\n",This,caps);
952
953         if (caps == NULL) {
954                 WARN("invalid parameter: caps == NULL\n");
955                 return DSERR_INVALIDPARAM;
956         }
957
958         if (caps->dwSize < sizeof(*caps)) {
959                 WARN("invalid parameter: caps->dwSize = %ld: < %d\n", caps->dwSize, sizeof(*caps));
960                 return DSERR_INVALIDPARAM;
961         }
962
963         caps->dwFlags = This->dsound->dsbd.dwFlags;
964         if (This->dsound->hwbuf) caps->dwFlags |= DSBCAPS_LOCHARDWARE;
965         else caps->dwFlags |= DSBCAPS_LOCSOFTWARE;
966
967         caps->dwBufferBytes = This->dsound->buflen;
968
969         /* This value represents the speed of the "unlock" command.
970            As unlock is quite fast (it does not do anything), I put
971            4096 ko/s = 4 Mo / s */
972         /* FIXME: hwbuf speed */
973         caps->dwUnlockTransferRate = 4096;
974         caps->dwPlayCpuOverhead = 0;
975
976         return DS_OK;
977 }
978
979 static HRESULT WINAPI PrimaryBufferImpl_QueryInterface(
980         LPDIRECTSOUNDBUFFER8 iface,REFIID riid,LPVOID *ppobj
981 ) {
982         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
983         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
984
985         if (ppobj == NULL) {
986                 WARN("invalid parameter\n");
987                 return E_INVALIDARG;
988         }
989
990         *ppobj = NULL;  /* assume failure */
991
992         if ( IsEqualGUID(riid, &IID_IUnknown) ||
993              IsEqualGUID(riid, &IID_IDirectSoundBuffer) ) {
994                 IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)This);
995                 *ppobj = This;
996                 return S_OK;
997         }
998
999         /* DirectSoundBuffer and DirectSoundBuffer8 are different and */
1000         /* a primary buffer can't have a DirectSoundBuffer8 interface */
1001         if ( IsEqualGUID( &IID_IDirectSoundBuffer8, riid ) ) {
1002                 WARN("app requested DirectSoundBuffer8 on primary buffer\n");
1003                 return E_NOINTERFACE;
1004         }
1005
1006         if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
1007                 ERR("app requested IDirectSoundNotify on primary buffer\n");
1008                 /* FIXME: should we support this? */
1009                 return E_NOINTERFACE;
1010         }
1011
1012         if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
1013                 ERR("app requested IDirectSound3DBuffer on primary buffer\n");
1014                 return E_NOINTERFACE;
1015         }
1016
1017         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
1018                 if (!This->dsound->listener)
1019                         IDirectSound3DListenerImpl_Create(This, &This->dsound->listener);
1020                 if (This->dsound->listener) {
1021                         *ppobj = This->dsound->listener;
1022                         IDirectSound3DListener_AddRef((LPDIRECTSOUND3DLISTENER)*ppobj);
1023                         return S_OK;
1024                 }
1025
1026                 WARN("IID_IDirectSound3DListener failed\n");
1027                 return E_NOINTERFACE;
1028         }
1029
1030         if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
1031                 FIXME("app requested IKsPropertySet on primary buffer\n");
1032                 return E_NOINTERFACE;
1033         }
1034
1035         FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
1036         return E_NOINTERFACE;
1037 }
1038
1039 static IDirectSoundBuffer8Vtbl dspbvt =
1040 {
1041         PrimaryBufferImpl_QueryInterface,
1042         PrimaryBufferImpl_AddRef,
1043         PrimaryBufferImpl_Release,
1044         PrimaryBufferImpl_GetCaps,
1045         PrimaryBufferImpl_GetCurrentPosition,
1046         PrimaryBufferImpl_GetFormat,
1047         PrimaryBufferImpl_GetVolume,
1048         PrimaryBufferImpl_GetPan,
1049         PrimaryBufferImpl_GetFrequency,
1050         PrimaryBufferImpl_GetStatus,
1051         PrimaryBufferImpl_Initialize,
1052         PrimaryBufferImpl_Lock,
1053         PrimaryBufferImpl_Play,
1054         PrimaryBufferImpl_SetCurrentPosition,
1055         PrimaryBufferImpl_SetFormat,
1056         PrimaryBufferImpl_SetVolume,
1057         PrimaryBufferImpl_SetPan,
1058         PrimaryBufferImpl_SetFrequency,
1059         PrimaryBufferImpl_Stop,
1060         PrimaryBufferImpl_Unlock,
1061         PrimaryBufferImpl_Restore,
1062         PrimaryBufferImpl_SetFX,
1063         PrimaryBufferImpl_AcquireResources,
1064         PrimaryBufferImpl_GetObjectInPath
1065 };
1066
1067 HRESULT WINAPI PrimaryBufferImpl_Create(
1068         IDirectSoundImpl *ds,
1069         PrimaryBufferImpl **pdsb,
1070         LPCDSBUFFERDESC dsbd)
1071 {
1072         PrimaryBufferImpl *dsb;
1073
1074         TRACE("%p,%p,%p)\n",ds,pdsb,dsbd);
1075
1076         if (dsbd->lpwfxFormat) {
1077                 WARN("invalid parameter: dsbd->lpwfxFormat != NULL\n");
1078                 *pdsb = NULL;
1079                 return DSERR_INVALIDPARAM;
1080         }
1081
1082         dsb = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*dsb));
1083
1084         if (dsb == NULL) {
1085                 WARN("out of memory\n");
1086                 *pdsb = NULL;
1087                 return DSERR_OUTOFMEMORY;
1088         }
1089
1090         dsb->ref = 0;
1091         dsb->dsound = ds;
1092         dsb->lpVtbl = &dspbvt;
1093
1094         memcpy(&ds->dsbd, dsbd, sizeof(*dsbd));
1095
1096         TRACE("Created primary buffer at %p\n", dsb);
1097         TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld,"
1098                 "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
1099                 ds->pwfx->wFormatTag, ds->pwfx->nChannels, ds->pwfx->nSamplesPerSec,
1100                 ds->pwfx->nAvgBytesPerSec, ds->pwfx->nBlockAlign,
1101                 ds->pwfx->wBitsPerSample, ds->pwfx->cbSize);
1102
1103         *pdsb = dsb;
1104         return S_OK;
1105 }