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