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