Use Windows memory functions.
[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                         FillMemory(This->buffer, This->buflen, (This->pwfx->wBitsPerSample == 16) ? 0 : 128);
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         HeapFree(GetProcessHeap(),0,This->pwfx);
238         This->pwfx=NULL;
239         return DS_OK;
240 }
241
242 HRESULT DSOUND_PrimaryPlay(IDirectSoundImpl *This)
243 {
244         HRESULT err = DS_OK;
245         TRACE("(%p)\n",This);
246
247         if (This->hwbuf) {
248                 err = IDsDriverBuffer_Play(This->hwbuf, 0, 0, DSBPLAY_LOOPING);
249                 if (err != DS_OK)
250                         WARN("IDsDriverBuffer_Play failed\n");
251         } else {
252                 err = mmErr(waveOutRestart(This->hwo));
253                 if (err != DS_OK)
254                         WARN("waveOutRestart failed\n");
255         }
256
257         return err;
258 }
259
260 HRESULT DSOUND_PrimaryStop(IDirectSoundImpl *This)
261 {
262         HRESULT err = DS_OK;
263         TRACE("(%p)\n",This);
264
265         if (This->hwbuf) {
266                 err = IDsDriverBuffer_Stop(This->hwbuf);
267                 if (err == DSERR_BUFFERLOST) {
268                         DWORD flags = CALLBACK_FUNCTION;
269                         if (ds_hw_accel != DS_HW_ACCEL_EMULATION)
270                                 flags |= WAVE_DIRECTSOUND;
271                         /* Wine-only: the driver wants us to reopen the device */
272                         /* FIXME: check for errors */
273                         IDsDriverBuffer_Release(This->hwbuf);
274                         waveOutClose(This->hwo);
275                         This->hwo = 0;
276                         err = mmErr(waveOutOpen(&(This->hwo), This->drvdesc.dnDevNode,
277                                                 This->pwfx, (DWORD)DSOUND_callback, (DWORD)This,
278                                                 flags));
279                         if (err == DS_OK) {
280                                 err = IDsDriver_CreateSoundBuffer(This->driver,This->pwfx,
281                                                                   DSBCAPS_PRIMARYBUFFER,0,
282                                                                   &(This->buflen),&(This->buffer),
283                                                                   (LPVOID)&(This->hwbuf));
284                                 if (err != DS_OK)
285                                         WARN("IDsDriver_CreateSoundBuffer failed\n");
286                         } else {
287                                 WARN("waveOutOpen failed\n");
288                         }
289                 } else if (err != DS_OK) {
290                         WARN("IDsDriverBuffer_Stop failed\n");
291                 }
292         } else {
293                 err = mmErr(waveOutPause(This->hwo));
294                 if (err != DS_OK)
295                         WARN("waveOutPause failed\n");
296         }
297         return err;
298 }
299
300 HRESULT DSOUND_PrimaryGetPosition(IDirectSoundImpl *This, LPDWORD playpos, LPDWORD writepos)
301 {
302         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
303
304         if (This->hwbuf) {
305                 HRESULT err=IDsDriverBuffer_GetPosition(This->hwbuf,playpos,writepos);
306                 if (err) {
307                         WARN("IDsDriverBuffer_GetPosition failed\n");
308                         return err;
309                 }
310         } else {
311                 if (playpos) {
312                         MMTIME mtime;
313                         mtime.wType = TIME_BYTES;
314                         waveOutGetPosition(This->hwo, &mtime, sizeof(mtime));
315                         mtime.u.cb = mtime.u.cb % This->buflen;
316                         *playpos = mtime.u.cb;
317                 }
318                 if (writepos) {
319                         /* the writepos should only be used by apps with WRITEPRIMARY priority,
320                          * in which case our software mixer is disabled anyway */
321                         *writepos = (This->pwplay + ds_hel_margin) * This->fraglen;
322                         while (*writepos >= This->buflen)
323                                 *writepos -= This->buflen;
324                 }
325         }
326         TRACE("playpos = %ld, writepos = %ld (%p, time=%ld)\n", playpos?*playpos:0, writepos?*writepos:0, This, GetTickCount());
327         return DS_OK;
328 }
329
330 /*******************************************************************************
331  *              PrimaryBuffer
332  */
333 /* This sets this format for the <em>Primary Buffer Only</em> */
334 /* See file:///cdrom/sdk52/docs/worddoc/dsound.doc page 120 */
335 static HRESULT WINAPI PrimaryBufferImpl_SetFormat(
336         LPDIRECTSOUNDBUFFER8 iface,LPCWAVEFORMATEX wfex
337 ) {
338         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
339         IDirectSoundImpl* dsound = This->dsound;
340         HRESULT err = DS_OK;
341         int i, alloc_size, cp_size;
342         DWORD nSamplesPerSec;
343         TRACE("(%p,%p)\n",This,wfex);
344
345         if (This->dsound->priolevel == DSSCL_NORMAL) {
346                 WARN("failed priority check!\n");
347                 return DSERR_PRIOLEVELNEEDED;
348         }
349
350         /* Let's be pedantic! */
351         if (wfex == NULL) {
352                 WARN("invalid parameter: wfex==NULL!\n");
353                 return DSERR_INVALIDPARAM;
354         }
355         TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld,"
356               "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
357               wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
358               wfex->nAvgBytesPerSec, wfex->nBlockAlign,
359               wfex->wBitsPerSample, wfex->cbSize);
360
361         /* **** */
362         RtlAcquireResourceExclusive(&(dsound->buffer_list_lock), TRUE);
363
364         if (wfex->wFormatTag == WAVE_FORMAT_PCM) {
365             alloc_size = sizeof(WAVEFORMATEX);
366             cp_size = sizeof(PCMWAVEFORMAT);
367         } else
368             alloc_size = cp_size = sizeof(WAVEFORMATEX) + wfex->cbSize;
369
370         dsound->pwfx = HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,dsound->pwfx,alloc_size);
371
372         nSamplesPerSec = dsound->pwfx->nSamplesPerSec;
373
374         CopyMemory(dsound->pwfx, wfex, cp_size);
375
376         if (dsound->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMSETFORMAT) {
377                 DWORD flags = CALLBACK_FUNCTION;
378                 if (ds_hw_accel != DS_HW_ACCEL_EMULATION)
379                         flags |= WAVE_DIRECTSOUND;
380                 /* FIXME: check for errors */
381                 DSOUND_PrimaryClose(dsound);
382                 waveOutClose(dsound->hwo);
383                 dsound->hwo = 0;
384                 err = mmErr(waveOutOpen(&(dsound->hwo), dsound->drvdesc.dnDevNode,
385                                         dsound->pwfx, (DWORD)DSOUND_callback, (DWORD)dsound,
386                                         flags));
387                 if (err == DS_OK) {
388                     err = DSOUND_PrimaryOpen(dsound);
389                     if (err != DS_OK) {
390                             WARN("DSOUND_PrimaryOpen failed\n");
391                             RtlReleaseResource(&(dsound->buffer_list_lock));
392                             return err;
393                     }
394                 } else {
395                         WARN("waveOutOpen failed\n");
396                         RtlReleaseResource(&(dsound->buffer_list_lock));
397                         return err;
398                 }
399         } else if (dsound->hwbuf) {
400                 err = IDsDriverBuffer_SetFormat(dsound->hwbuf, dsound->pwfx);
401                 if (err == DSERR_BUFFERLOST) {
402                         /* Wine-only: the driver wants us to recreate the HW buffer */
403                         IDsDriverBuffer_Release(dsound->hwbuf);
404                         err = IDsDriver_CreateSoundBuffer(dsound->driver,dsound->pwfx,
405                                                           DSBCAPS_PRIMARYBUFFER,0,
406                                                           &(dsound->buflen),&(dsound->buffer),
407                                                           (LPVOID)&(dsound->hwbuf));
408                         if (err != DS_OK) {
409                                 WARN("IDsDriver_CreateSoundBuffer failed\n");
410                                 RtlReleaseResource(&(dsound->buffer_list_lock));
411                                 return err;
412                         }
413                         if (dsound->state == STATE_PLAYING) dsound->state = STATE_STARTING;
414                         else if (dsound->state == STATE_STOPPING) dsound->state = STATE_STOPPED;
415                 } else {
416                         WARN("IDsDriverBuffer_SetFormat failed\n");
417                         RtlReleaseResource(&(dsound->buffer_list_lock));
418                         return err;
419                 }
420                 /* FIXME: should we set err back to DS_OK in all cases ? */
421         }
422         DSOUND_RecalcPrimary(dsound);
423
424         if (nSamplesPerSec != dsound->pwfx->nSamplesPerSec) {
425                 IDirectSoundBufferImpl** dsb = dsound->buffers;
426                 for (i = 0; i < dsound->nrofbuffers; i++, dsb++) {
427                         /* **** */
428                         EnterCriticalSection(&((*dsb)->lock));
429
430                         (*dsb)->freqAdjust = ((*dsb)->freq << DSOUND_FREQSHIFT) /
431                                 wfex->nSamplesPerSec;
432
433                         LeaveCriticalSection(&((*dsb)->lock));
434                         /* **** */
435                 }
436         }
437
438         RtlReleaseResource(&(dsound->buffer_list_lock));
439         /* **** */
440
441         return err;
442 }
443
444 static HRESULT WINAPI PrimaryBufferImpl_SetVolume(
445         LPDIRECTSOUNDBUFFER8 iface,LONG vol
446 ) {
447         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
448         IDirectSoundImpl* dsound = This->dsound;
449         DWORD ampfactors;
450         DSVOLUMEPAN volpan;
451         HRESULT hres = DS_OK;
452
453         TRACE("(%p,%ld)\n",This,vol);
454
455         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
456                 WARN("control unavailable\n");
457                 return DSERR_CONTROLUNAVAIL;
458         }
459
460         if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN)) {
461                 WARN("invalid parameter: vol = %ld\n", vol);
462                 return DSERR_INVALIDPARAM;
463         }
464
465         /* **** */
466         EnterCriticalSection(&(dsound->mixlock));
467
468         waveOutGetVolume(dsound->hwo, &ampfactors);
469         volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
470         volpan.dwTotalRightAmpFactor=ampfactors >> 16;
471         DSOUND_AmpFactorToVolPan(&volpan);
472         if (vol != volpan.lVolume) {
473             volpan.lVolume=vol;
474             DSOUND_RecalcVolPan(&volpan);
475             if (dsound->hwbuf) {
476                 hres = IDsDriverBuffer_SetVolumePan(dsound->hwbuf, &volpan);
477                 if (hres != DS_OK)
478                     WARN("IDsDriverBuffer_SetVolumePan failed\n");
479             } else {
480                 ampfactors = (volpan.dwTotalLeftAmpFactor & 0xffff) | (volpan.dwTotalRightAmpFactor << 16);
481                 waveOutSetVolume(dsound->hwo, ampfactors);
482             }
483         }
484
485         LeaveCriticalSection(&(dsound->mixlock));
486         /* **** */
487
488         return hres;
489 }
490
491 static HRESULT WINAPI PrimaryBufferImpl_GetVolume(
492         LPDIRECTSOUNDBUFFER8 iface,LPLONG vol
493 ) {
494         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
495         DWORD ampfactors;
496         DSVOLUMEPAN volpan;
497         TRACE("(%p,%p)\n",This,vol);
498
499         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
500                 WARN("control unavailable\n");
501                 return DSERR_CONTROLUNAVAIL;
502         }
503
504         if (vol == NULL) {
505                 WARN("invalid parameter: vol = NULL\n");
506                 return DSERR_INVALIDPARAM;
507         }
508
509         waveOutGetVolume(dsound->hwo, &ampfactors);
510         volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
511         volpan.dwTotalRightAmpFactor=ampfactors >> 16;
512         DSOUND_AmpFactorToVolPan(&volpan);
513         *vol = volpan.lVolume;
514         return DS_OK;
515 }
516
517 static HRESULT WINAPI PrimaryBufferImpl_SetFrequency(
518         LPDIRECTSOUNDBUFFER8 iface,DWORD freq
519 ) {
520         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
521
522         TRACE("(%p,%ld)\n",This,freq);
523
524         /* You cannot set the frequency of the primary buffer */
525         WARN("control unavailable\n");
526         return DSERR_CONTROLUNAVAIL;
527 }
528
529 static HRESULT WINAPI PrimaryBufferImpl_Play(
530         LPDIRECTSOUNDBUFFER8 iface,DWORD reserved1,DWORD reserved2,DWORD flags
531 ) {
532         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
533         IDirectSoundImpl* dsound = This->dsound;
534
535         TRACE("(%p,%08lx,%08lx,%08lx)\n",
536                 This,reserved1,reserved2,flags
537         );
538
539         if (!(flags & DSBPLAY_LOOPING)) {
540                 WARN("invalid parameter: flags = %08lx\n", flags);
541                 return DSERR_INVALIDPARAM;
542         }
543
544         /* **** */
545         EnterCriticalSection(&(dsound->mixlock));
546
547         if (dsound->state == STATE_STOPPED)
548                 dsound->state = STATE_STARTING;
549         else if (dsound->state == STATE_STOPPING)
550                 dsound->state = STATE_PLAYING;
551
552         LeaveCriticalSection(&(dsound->mixlock));
553         /* **** */
554
555         return DS_OK;
556 }
557
558 static HRESULT WINAPI PrimaryBufferImpl_Stop(LPDIRECTSOUNDBUFFER8 iface)
559 {
560         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
561         IDirectSoundImpl* dsound = This->dsound;
562
563         TRACE("(%p)\n",This);
564
565         /* **** */
566         EnterCriticalSection(&(dsound->mixlock));
567
568         if (dsound->state == STATE_PLAYING)
569                 dsound->state = STATE_STOPPING;
570         else if (dsound->state == STATE_STARTING)
571                 dsound->state = STATE_STOPPED;
572
573         LeaveCriticalSection(&(dsound->mixlock));
574         /* **** */
575
576         return DS_OK;
577 }
578
579 static ULONG WINAPI PrimaryBufferImpl_AddRef(LPDIRECTSOUNDBUFFER8 iface) {
580         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
581         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
582         return InterlockedIncrement(&(This->ref));
583 }
584
585 static ULONG WINAPI PrimaryBufferImpl_Release(LPDIRECTSOUNDBUFFER8 iface) {
586         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
587         DWORD ref;
588
589         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
590         ref = InterlockedDecrement(&(This->ref));
591
592         if (ref == 0) {
593                 This->dsound->primary = NULL;
594                 HeapFree(GetProcessHeap(),0,This);
595                 TRACE("(%p) released\n",This);
596         }
597
598         return ref;
599 }
600
601 static HRESULT WINAPI PrimaryBufferImpl_GetCurrentPosition(
602         LPDIRECTSOUNDBUFFER8 iface,LPDWORD playpos,LPDWORD writepos
603 ) {
604         HRESULT hres;
605         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
606         IDirectSoundImpl* dsound = This->dsound;
607
608         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
609         hres = DSOUND_PrimaryGetPosition(dsound, playpos, writepos);
610         if (hres != DS_OK) {
611                 WARN("DSOUND_PrimaryGetPosition failed\n");
612                 return hres;
613         }
614         if (writepos) {
615                 if (dsound->state != STATE_STOPPED)
616                         /* apply the documented 10ms lead to writepos */
617                         *writepos += dsound->writelead;
618                 while (*writepos >= dsound->buflen) *writepos -= dsound->buflen;
619         }
620         TRACE("playpos = %ld, writepos = %ld (%p, time=%ld)\n", playpos?*playpos:0, writepos?*writepos:0, This, GetTickCount());
621         return DS_OK;
622 }
623
624 static HRESULT WINAPI PrimaryBufferImpl_GetStatus(
625         LPDIRECTSOUNDBUFFER8 iface,LPDWORD status
626 ) {
627         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
628         TRACE("(%p,%p), thread is %04lx\n",This,status,GetCurrentThreadId());
629
630         if (status == NULL) {
631                 WARN("invalid parameter: status == NULL\n");
632                 return DSERR_INVALIDPARAM;
633         }
634
635         *status = 0;
636         if ((This->dsound->state == STATE_STARTING) ||
637             (This->dsound->state == STATE_PLAYING))
638                 *status |= DSBSTATUS_PLAYING | DSBSTATUS_LOOPING;
639
640         TRACE("status=%lx\n", *status);
641         return DS_OK;
642 }
643
644
645 static HRESULT WINAPI PrimaryBufferImpl_GetFormat(
646     LPDIRECTSOUNDBUFFER8 iface,
647     LPWAVEFORMATEX lpwf,
648     DWORD wfsize,
649     LPDWORD wfwritten)
650 {
651     DWORD size;
652     PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
653     TRACE("(%p,%p,%ld,%p)\n",This,lpwf,wfsize,wfwritten);
654
655     size = sizeof(WAVEFORMATEX) + This->dsound->pwfx->cbSize;
656
657     if (lpwf) { /* NULL is valid */
658         if (wfsize >= size) {
659             CopyMemory(lpwf,This->dsound->pwfx,size);
660             if (wfwritten)
661                 *wfwritten = size;
662         } else {
663             WARN("invalid parameter: wfsize to small\n");
664             if (wfwritten)
665                 *wfwritten = 0;
666             return DSERR_INVALIDPARAM;
667         }
668     } else {
669         if (wfwritten)
670             *wfwritten = sizeof(WAVEFORMATEX) + This->dsound->pwfx->cbSize;
671         else {
672             WARN("invalid parameter: wfwritten == NULL\n");
673             return DSERR_INVALIDPARAM;
674         }
675     }
676
677     return DS_OK;
678 }
679
680 static HRESULT WINAPI PrimaryBufferImpl_Lock(
681         LPDIRECTSOUNDBUFFER8 iface,DWORD writecursor,DWORD writebytes,LPVOID lplpaudioptr1,LPDWORD audiobytes1,LPVOID lplpaudioptr2,LPDWORD audiobytes2,DWORD flags
682 ) {
683         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
684         IDirectSoundImpl* dsound = This->dsound;
685
686         TRACE("(%p,%ld,%ld,%p,%p,%p,%p,0x%08lx) at %ld\n",
687                 This,
688                 writecursor,
689                 writebytes,
690                 lplpaudioptr1,
691                 audiobytes1,
692                 lplpaudioptr2,
693                 audiobytes2,
694                 flags,
695                 GetTickCount()
696         );
697
698         if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
699                 WARN("failed priority check!\n");
700                 return DSERR_PRIOLEVELNEEDED;
701         }
702
703         if (flags & DSBLOCK_FROMWRITECURSOR) {
704                 DWORD writepos;
705                 HRESULT hres;
706                 /* GetCurrentPosition does too much magic to duplicate here */
707                 hres = IDirectSoundBuffer_GetCurrentPosition(iface, NULL, &writepos);
708                 if (hres != DS_OK) {
709                         WARN("IDirectSoundBuffer_GetCurrentPosition failed\n");
710                         return hres;
711                 }
712                 writecursor += writepos;
713         }
714         while (writecursor >= dsound->buflen)
715                 writecursor -= dsound->buflen;
716         if (flags & DSBLOCK_ENTIREBUFFER)
717                 writebytes = dsound->buflen;
718         if (writebytes > dsound->buflen)
719                 writebytes = dsound->buflen;
720
721         if (!(dsound->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK) && dsound->hwbuf) {
722                 HRESULT hres;
723                 hres = IDsDriverBuffer_Lock(dsound->hwbuf,
724                                             lplpaudioptr1, audiobytes1,
725                                             lplpaudioptr2, audiobytes2,
726                                             writecursor, writebytes,
727                                             0);
728                 if (hres != DS_OK) {
729                         WARN("IDsDriverBuffer_Lock failed\n");
730                         return hres;
731                 }
732         } else {
733                 if (writecursor+writebytes <= dsound->buflen) {
734                         *(LPBYTE*)lplpaudioptr1 = dsound->buffer+writecursor;
735                         *audiobytes1 = writebytes;
736                         if (lplpaudioptr2)
737                                 *(LPBYTE*)lplpaudioptr2 = NULL;
738                         if (audiobytes2)
739                                 *audiobytes2 = 0;
740                         TRACE("->%ld.0\n",writebytes);
741                 } else {
742                         *(LPBYTE*)lplpaudioptr1 = dsound->buffer+writecursor;
743                         *audiobytes1 = dsound->buflen-writecursor;
744                         if (lplpaudioptr2)
745                                 *(LPBYTE*)lplpaudioptr2 = dsound->buffer;
746                         if (audiobytes2)
747                                 *audiobytes2 = writebytes-(dsound->buflen-writecursor);
748                         TRACE("->%ld.%ld\n",*audiobytes1,audiobytes2?*audiobytes2:0);
749                 }
750         }
751         return DS_OK;
752 }
753
754 static HRESULT WINAPI PrimaryBufferImpl_SetCurrentPosition(
755         LPDIRECTSOUNDBUFFER8 iface,DWORD newpos
756 ) {
757         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
758         TRACE("(%p,%ld)\n",This,newpos);
759
760         /* You cannot set the position of the primary buffer */
761         WARN("invalid call\n");
762         return DSERR_INVALIDCALL;
763 }
764
765 static HRESULT WINAPI PrimaryBufferImpl_SetPan(
766         LPDIRECTSOUNDBUFFER8 iface,LONG pan
767 ) {
768         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
769         IDirectSoundImpl* dsound = This->dsound;
770         DWORD ampfactors;
771         DSVOLUMEPAN volpan;
772         HRESULT hres = DS_OK;
773
774         TRACE("(%p,%ld)\n",This,pan);
775
776         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
777                 WARN("control unavailable\n");
778                 return DSERR_CONTROLUNAVAIL;
779         }
780
781         if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT)) {
782                 WARN("invalid parameter: pan = %ld\n", pan);
783                 return DSERR_INVALIDPARAM;
784         }
785
786         /* **** */
787         EnterCriticalSection(&(dsound->mixlock));
788
789         waveOutGetVolume(dsound->hwo, &ampfactors);
790         volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
791         volpan.dwTotalRightAmpFactor=ampfactors >> 16;
792         DSOUND_AmpFactorToVolPan(&volpan);
793         if (pan != volpan.lPan) {
794             volpan.lPan=pan;
795             DSOUND_RecalcVolPan(&volpan);
796             if (dsound->hwbuf) {
797                 hres = IDsDriverBuffer_SetVolumePan(dsound->hwbuf, &volpan);
798                 if (hres != DS_OK)
799                     WARN("IDsDriverBuffer_SetVolumePan failed\n");
800             } else {
801                 ampfactors = (volpan.dwTotalLeftAmpFactor & 0xffff) | (volpan.dwTotalRightAmpFactor << 16);
802                 waveOutSetVolume(dsound->hwo, ampfactors);
803             }
804         }
805
806         LeaveCriticalSection(&(dsound->mixlock));
807         /* **** */
808
809         return hres;
810 }
811
812 static HRESULT WINAPI PrimaryBufferImpl_GetPan(
813         LPDIRECTSOUNDBUFFER8 iface,LPLONG pan
814 ) {
815         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
816         DWORD ampfactors;
817         DSVOLUMEPAN volpan;
818         TRACE("(%p,%p)\n",This,pan);
819
820         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
821                 WARN("control unavailable\n");
822                 return DSERR_CONTROLUNAVAIL;
823         }
824
825         if (pan == NULL) {
826                 WARN("invalid parameter: pan == NULL\n");
827                 return DSERR_INVALIDPARAM;
828         }
829
830         waveOutGetVolume(dsound->hwo, &ampfactors);
831         volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
832         volpan.dwTotalRightAmpFactor=ampfactors >> 16;
833         DSOUND_AmpFactorToVolPan(&volpan);
834         *pan = volpan.lPan;
835         return DS_OK;
836 }
837
838 static HRESULT WINAPI PrimaryBufferImpl_Unlock(
839         LPDIRECTSOUNDBUFFER8 iface,LPVOID p1,DWORD x1,LPVOID p2,DWORD x2
840 ) {
841         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
842         IDirectSoundImpl* dsound = This->dsound;
843
844         TRACE("(%p,%p,%ld,%p,%ld)\n", This,p1,x1,p2,x2);
845
846         if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
847                 WARN("failed priority check!\n");
848                 return DSERR_PRIOLEVELNEEDED;
849         }
850
851         if (!(dsound->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK) && dsound->hwbuf) {
852                 HRESULT hres;
853                 
854                 hres = IDsDriverBuffer_Unlock(dsound->hwbuf, p1, x1, p2, x2);
855                 if (hres != DS_OK) {
856                         WARN("IDsDriverBuffer_Unlock failed\n");
857                         return hres;
858                 }
859         }
860
861         return DS_OK;
862 }
863
864 static HRESULT WINAPI PrimaryBufferImpl_Restore(
865         LPDIRECTSOUNDBUFFER8 iface
866 ) {
867         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
868         FIXME("(%p):stub\n",This);
869         return DS_OK;
870 }
871
872 static HRESULT WINAPI PrimaryBufferImpl_GetFrequency(
873         LPDIRECTSOUNDBUFFER8 iface,LPDWORD freq
874 ) {
875         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
876         TRACE("(%p,%p)\n",This,freq);
877
878         if (freq == NULL) {
879                 WARN("invalid parameter: freq == NULL\n");
880                 return DSERR_INVALIDPARAM;
881         }
882
883         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) {
884                 WARN("control unavailable\n");
885                 return DSERR_CONTROLUNAVAIL;
886         }
887
888         *freq = This->dsound->pwfx->nSamplesPerSec;
889         TRACE("-> %ld\n", *freq);
890
891         return DS_OK;
892 }
893
894 static HRESULT WINAPI PrimaryBufferImpl_SetFX(
895         LPDIRECTSOUNDBUFFER8 iface,DWORD dwEffectsCount,LPDSEFFECTDESC pDSFXDesc,LPDWORD pdwResultCodes
896 ) {
897         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
898         DWORD u;
899
900         FIXME("(%p,%lu,%p,%p): stub\n",This,dwEffectsCount,pDSFXDesc,pdwResultCodes);
901
902         if (pdwResultCodes)
903                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
904
905         WARN("control unavailable\n");
906         return DSERR_CONTROLUNAVAIL;
907 }
908
909 static HRESULT WINAPI PrimaryBufferImpl_AcquireResources(
910         LPDIRECTSOUNDBUFFER8 iface,DWORD dwFlags,DWORD dwEffectsCount,LPDWORD pdwResultCodes
911 ) {
912         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
913         DWORD u;
914
915         FIXME("(%p,%08lu,%lu,%p): stub\n",This,dwFlags,dwEffectsCount,pdwResultCodes);
916
917         if (pdwResultCodes)
918                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
919
920         WARN("control unavailable\n");
921         return DSERR_CONTROLUNAVAIL;
922 }
923
924 static HRESULT WINAPI PrimaryBufferImpl_GetObjectInPath(
925         LPDIRECTSOUNDBUFFER8 iface,REFGUID rguidObject,DWORD dwIndex,REFGUID rguidInterface,LPVOID* ppObject
926 ) {
927         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
928
929         FIXME("(%p,%s,%lu,%s,%p): stub\n",This,debugstr_guid(rguidObject),dwIndex,debugstr_guid(rguidInterface),ppObject);
930
931         WARN("control unavailable\n");
932         return DSERR_CONTROLUNAVAIL;
933 }
934
935 static HRESULT WINAPI PrimaryBufferImpl_Initialize(
936         LPDIRECTSOUNDBUFFER8 iface,LPDIRECTSOUND dsound,LPCDSBUFFERDESC dbsd
937 ) {
938         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
939         FIXME("(%p,%p,%p):stub\n",This,dsound,dbsd);
940         DPRINTF("Re-Init!!!\n");
941         WARN("already initialized\n");
942         return DSERR_ALREADYINITIALIZED;
943 }
944
945 static HRESULT WINAPI PrimaryBufferImpl_GetCaps(
946         LPDIRECTSOUNDBUFFER8 iface,LPDSBCAPS caps
947 ) {
948         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
949         TRACE("(%p)->(%p)\n",This,caps);
950
951         if (caps == NULL) {
952                 WARN("invalid parameter: caps == NULL\n");
953                 return DSERR_INVALIDPARAM;
954         }
955
956         if (caps->dwSize < sizeof(*caps)) {
957                 WARN("invalid parameter: caps->dwSize = %ld: < %d\n", caps->dwSize, sizeof(*caps));
958                 return DSERR_INVALIDPARAM;
959         }
960
961         caps->dwFlags = This->dsound->dsbd.dwFlags;
962         if (This->dsound->hwbuf) caps->dwFlags |= DSBCAPS_LOCHARDWARE;
963         else caps->dwFlags |= DSBCAPS_LOCSOFTWARE;
964
965         caps->dwBufferBytes = This->dsound->buflen;
966
967         /* This value represents the speed of the "unlock" command.
968            As unlock is quite fast (it does not do anything), I put
969            4096 ko/s = 4 Mo / s */
970         /* FIXME: hwbuf speed */
971         caps->dwUnlockTransferRate = 4096;
972         caps->dwPlayCpuOverhead = 0;
973
974         return DS_OK;
975 }
976
977 static HRESULT WINAPI PrimaryBufferImpl_QueryInterface(
978         LPDIRECTSOUNDBUFFER8 iface,REFIID riid,LPVOID *ppobj
979 ) {
980         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
981         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
982
983         if (ppobj == NULL) {
984                 WARN("invalid parameter\n");
985                 return E_INVALIDARG;
986         }
987
988         *ppobj = NULL;  /* assume failure */
989
990         if ( IsEqualGUID(riid, &IID_IUnknown) ||
991              IsEqualGUID(riid, &IID_IDirectSoundBuffer) ) {
992                 IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)This);
993                 *ppobj = This;
994                 return S_OK;
995         }
996
997         /* DirectSoundBuffer and DirectSoundBuffer8 are different and */
998         /* a primary buffer can't have a DirectSoundBuffer8 interface */
999         if ( IsEqualGUID( &IID_IDirectSoundBuffer8, riid ) ) {
1000                 WARN("app requested DirectSoundBuffer8 on primary buffer\n");
1001                 return E_NOINTERFACE;
1002         }
1003
1004         if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
1005                 ERR("app requested IDirectSoundNotify on primary buffer\n");
1006                 /* FIXME: should we support this? */
1007                 return E_NOINTERFACE;
1008         }
1009
1010         if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
1011                 ERR("app requested IDirectSound3DBuffer on primary buffer\n");
1012                 return E_NOINTERFACE;
1013         }
1014
1015         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
1016                 if (!This->dsound->listener)
1017                         IDirectSound3DListenerImpl_Create(This, &This->dsound->listener);
1018                 if (This->dsound->listener) {
1019                         *ppobj = This->dsound->listener;
1020                         IDirectSound3DListener_AddRef((LPDIRECTSOUND3DLISTENER)*ppobj);
1021                         return S_OK;
1022                 }
1023
1024                 WARN("IID_IDirectSound3DListener failed\n");
1025                 return E_NOINTERFACE;
1026         }
1027
1028         if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
1029                 FIXME("app requested IKsPropertySet on primary buffer\n");
1030                 return E_NOINTERFACE;
1031         }
1032
1033         FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
1034         return E_NOINTERFACE;
1035 }
1036
1037 static IDirectSoundBuffer8Vtbl dspbvt =
1038 {
1039         PrimaryBufferImpl_QueryInterface,
1040         PrimaryBufferImpl_AddRef,
1041         PrimaryBufferImpl_Release,
1042         PrimaryBufferImpl_GetCaps,
1043         PrimaryBufferImpl_GetCurrentPosition,
1044         PrimaryBufferImpl_GetFormat,
1045         PrimaryBufferImpl_GetVolume,
1046         PrimaryBufferImpl_GetPan,
1047         PrimaryBufferImpl_GetFrequency,
1048         PrimaryBufferImpl_GetStatus,
1049         PrimaryBufferImpl_Initialize,
1050         PrimaryBufferImpl_Lock,
1051         PrimaryBufferImpl_Play,
1052         PrimaryBufferImpl_SetCurrentPosition,
1053         PrimaryBufferImpl_SetFormat,
1054         PrimaryBufferImpl_SetVolume,
1055         PrimaryBufferImpl_SetPan,
1056         PrimaryBufferImpl_SetFrequency,
1057         PrimaryBufferImpl_Stop,
1058         PrimaryBufferImpl_Unlock,
1059         PrimaryBufferImpl_Restore,
1060         PrimaryBufferImpl_SetFX,
1061         PrimaryBufferImpl_AcquireResources,
1062         PrimaryBufferImpl_GetObjectInPath
1063 };
1064
1065 HRESULT WINAPI PrimaryBufferImpl_Create(
1066         IDirectSoundImpl *ds,
1067         PrimaryBufferImpl **pdsb,
1068         LPCDSBUFFERDESC dsbd)
1069 {
1070         PrimaryBufferImpl *dsb;
1071
1072         TRACE("%p,%p,%p)\n",ds,pdsb,dsbd);
1073
1074         if (dsbd->lpwfxFormat) {
1075                 WARN("invalid parameter: dsbd->lpwfxFormat != NULL\n");
1076                 *pdsb = NULL;
1077                 return DSERR_INVALIDPARAM;
1078         }
1079
1080         dsb = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*dsb));
1081
1082         if (dsb == NULL) {
1083                 WARN("out of memory\n");
1084                 *pdsb = NULL;
1085                 return DSERR_OUTOFMEMORY;
1086         }
1087
1088         dsb->ref = 0;
1089         dsb->dsound = ds;
1090         dsb->lpVtbl = &dspbvt;
1091
1092         CopyMemory(&ds->dsbd, dsbd, sizeof(*dsbd));
1093
1094         TRACE("Created primary buffer at %p\n", dsb);
1095         TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld,"
1096                 "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
1097                 ds->pwfx->wFormatTag, ds->pwfx->nChannels, ds->pwfx->nSamplesPerSec,
1098                 ds->pwfx->nAvgBytesPerSec, ds->pwfx->nBlockAlign,
1099                 ds->pwfx->wBitsPerSample, ds->pwfx->cbSize);
1100
1101         *pdsb = dsb;
1102         return S_OK;
1103 }