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