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