urlmon/tests: Fix a failure on Win98.
[wine.git] / dlls / dsound / primary.c
blob8a054f8660720f2401870704e70c27bd1c198a04
1 /* DirectSound
3 * Copyright 1998 Marcus Meissner
4 * Copyright 1998 Rob Riggs
5 * Copyright 2000-2002 TransGaming Technologies, Inc.
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.
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.
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
21 * TODO:
22 * When PrimarySetFormat (via ReopenDevice or PrimaryOpen) fails,
23 * it leaves dsound in unusable (not really open) state.
26 #include <stdarg.h>
28 #define NONAMELESSSTRUCT
29 #define NONAMELESSUNION
30 #include "windef.h"
31 #include "winbase.h"
32 #include "winuser.h"
33 #include "mmsystem.h"
34 #include "winternl.h"
35 #include "mmddk.h"
36 #include "wine/debug.h"
37 #include "dsound.h"
38 #include "dsdriver.h"
39 #include "dsound_private.h"
41 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
43 /** Calculate how long a fragment length of about 10 ms should be in frames
45 * nSamplesPerSec: Frequency rate in samples per second
46 * nBlockAlign: Size of a single blockalign
48 * Returns:
49 * Size in bytes of a single fragment
51 DWORD DSOUND_fraglen(DWORD nSamplesPerSec, DWORD nBlockAlign)
53 /* Given a timer delay of 10ms, the fragment size is approximately:
54 * fraglen = (nSamplesPerSec * 10 / 1000) * nBlockAlign
55 * ==> fraglen = (nSamplesPerSec / 100) * nBlockSize
57 * ALSA uses buffers that are powers of 2. Because of this, fraglen
58 * is rounded up to the nearest power of 2:
61 if (nSamplesPerSec <= 12800)
62 return 128 * nBlockAlign;
64 if (nSamplesPerSec <= 25600)
65 return 256 * nBlockAlign;
67 if (nSamplesPerSec <= 51200)
68 return 512 * nBlockAlign;
70 return 1024 * nBlockAlign;
73 static void DSOUND_RecalcPrimary(DirectSoundDevice *device)
75 TRACE("(%p)\n", device);
77 device->fraglen = DSOUND_fraglen(device->pwfx->nSamplesPerSec, device->pwfx->nBlockAlign);
78 device->helfrags = device->buflen / device->fraglen;
79 TRACE("fraglen=%d helfrags=%d\n", device->fraglen, device->helfrags);
81 if (device->hwbuf && device->drvdesc.dwFlags & DSDDESC_DONTNEEDWRITELEAD)
82 device->writelead = 0;
83 else
84 /* calculate the 10ms write lead */
85 device->writelead = (device->pwfx->nSamplesPerSec / 100) * device->pwfx->nBlockAlign;
88 HRESULT DSOUND_ReopenDevice(DirectSoundDevice *device, BOOL forcewave)
90 HRESULT hres = DS_OK;
91 TRACE("(%p, %d)\n", device, forcewave);
93 if (device->driver)
95 IDsDriver_Close(device->driver);
96 if (device->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMOPEN)
97 waveOutClose(device->hwo);
98 IDsDriver_Release(device->driver);
99 device->driver = NULL;
100 device->buffer = NULL;
101 device->hwo = 0;
103 else if (device->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMOPEN)
104 waveOutClose(device->hwo);
106 /* DRV_QUERYDSOUNDIFACE is a "Wine extension" to get the DSound interface */
107 if (ds_hw_accel != DS_HW_ACCEL_EMULATION && !forcewave)
108 waveOutMessage((HWAVEOUT)device->drvdesc.dnDevNode, DRV_QUERYDSOUNDIFACE, (DWORD_PTR)&device->driver, 0);
110 /* Get driver description */
111 if (device->driver) {
112 DWORD wod = device->drvdesc.dnDevNode;
113 hres = IDsDriver_GetDriverDesc(device->driver,&(device->drvdesc));
114 device->drvdesc.dnDevNode = wod;
115 if (FAILED(hres)) {
116 WARN("IDsDriver_GetDriverDesc failed: %08x\n", hres);
117 IDsDriver_Release(device->driver);
118 device->driver = NULL;
122 /* if no DirectSound interface available, use WINMM API instead */
123 if (!device->driver)
124 device->drvdesc.dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT;
126 if (device->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMOPEN)
128 DWORD flags = CALLBACK_FUNCTION;
130 if (device->driver)
131 flags |= WAVE_DIRECTSOUND;
133 hres = mmErr(waveOutOpen(&(device->hwo), device->drvdesc.dnDevNode, device->pwfx, (DWORD_PTR)DSOUND_callback, (DWORD_PTR)device, flags));
134 if (FAILED(hres)) {
135 WARN("waveOutOpen failed\n");
136 if (device->driver)
138 IDsDriver_Release(device->driver);
139 device->driver = NULL;
141 return hres;
145 if (device->driver)
146 hres = IDsDriver_Open(device->driver);
148 return hres;
151 static HRESULT DSOUND_PrimaryOpen(DirectSoundDevice *device)
153 DWORD buflen;
154 HRESULT err = DS_OK;
155 TRACE("(%p)\n", device);
157 /* on original windows, the buffer it set to a fixed size, no matter what the settings are.
158 on windows this size is always fixed (tested on win-xp) */
159 if (!device->buflen)
160 device->buflen = ds_hel_buflen;
161 buflen = device->buflen;
162 buflen -= buflen % device->pwfx->nBlockAlign;
163 device->buflen = buflen;
165 if (device->driver)
167 err = IDsDriver_CreateSoundBuffer(device->driver,device->pwfx,
168 DSBCAPS_PRIMARYBUFFER,0,
169 &(device->buflen),&(device->buffer),
170 (LPVOID*)&(device->hwbuf));
172 if (err != DS_OK) {
173 WARN("IDsDriver_CreateSoundBuffer failed (%08x), falling back to waveout\n", err);
174 err = DSOUND_ReopenDevice(device, TRUE);
175 if (FAILED(err))
177 WARN("Falling back to waveout failed too! Giving up\n");
178 return err;
181 if (device->hwbuf)
182 IDsDriverBuffer_SetVolumePan(device->hwbuf, &device->volpan);
184 DSOUND_RecalcPrimary(device);
185 device->prebuf = ds_snd_queue_max;
186 if (device->helfrags < ds_snd_queue_min)
188 WARN("Too little sound buffer to be effective (%d/%d) falling back to waveout\n", device->buflen, ds_snd_queue_min * device->fraglen);
189 device->buflen = buflen;
190 IDsDriverBuffer_Release(device->hwbuf);
191 device->hwbuf = NULL;
192 err = DSOUND_ReopenDevice(device, TRUE);
193 if (FAILED(err))
195 WARN("Falling back to waveout failed too! Giving up\n");
196 return err;
199 else if (device->helfrags < ds_snd_queue_max)
200 device->prebuf = device->helfrags;
203 device->mix_buffer_len = DSOUND_bufpos_to_mixpos(device, device->buflen);
204 device->mix_buffer = HeapAlloc(GetProcessHeap(), 0, device->mix_buffer_len);
205 if (!device->mix_buffer)
207 if (device->hwbuf)
208 IDsDriverBuffer_Release(device->hwbuf);
209 device->hwbuf = NULL;
210 return DSERR_OUTOFMEMORY;
213 if (device->state == STATE_PLAYING) device->state = STATE_STARTING;
214 else if (device->state == STATE_STOPPING) device->state = STATE_STOPPED;
216 /* are we using waveOut stuff? */
217 if (!device->driver) {
218 LPBYTE newbuf;
219 LPWAVEHDR headers = NULL;
220 DWORD overshot;
221 unsigned int c;
223 /* Start in pause mode, to allow buffers to get filled */
224 waveOutPause(device->hwo);
226 TRACE("desired buflen=%d, old buffer=%p\n", buflen, device->buffer);
228 /* reallocate emulated primary buffer */
229 if (device->buffer)
230 newbuf = HeapReAlloc(GetProcessHeap(),0,device->buffer, buflen);
231 else
232 newbuf = HeapAlloc(GetProcessHeap(),0, buflen);
234 if (!newbuf) {
235 ERR("failed to allocate primary buffer\n");
236 return DSERR_OUTOFMEMORY;
237 /* but the old buffer might still exist and must be re-prepared */
240 DSOUND_RecalcPrimary(device);
241 if (device->pwave)
242 headers = HeapReAlloc(GetProcessHeap(),0,device->pwave, device->helfrags * sizeof(WAVEHDR));
243 else
244 headers = HeapAlloc(GetProcessHeap(),0,device->helfrags * sizeof(WAVEHDR));
246 if (!headers) {
247 ERR("failed to allocate wave headers\n");
248 HeapFree(GetProcessHeap(), 0, newbuf);
249 DSOUND_RecalcPrimary(device);
250 return DSERR_OUTOFMEMORY;
253 device->buffer = newbuf;
254 device->pwave = headers;
256 /* prepare fragment headers */
257 for (c=0; c<device->helfrags; c++) {
258 device->pwave[c].lpData = (char*)device->buffer + c*device->fraglen;
259 device->pwave[c].dwBufferLength = device->fraglen;
260 device->pwave[c].dwUser = (DWORD_PTR)device;
261 device->pwave[c].dwFlags = 0;
262 device->pwave[c].dwLoops = 0;
263 err = mmErr(waveOutPrepareHeader(device->hwo,&device->pwave[c],sizeof(WAVEHDR)));
264 if (err != DS_OK) {
265 while (c--)
266 waveOutUnprepareHeader(device->hwo,&device->pwave[c],sizeof(WAVEHDR));
267 break;
271 overshot = device->buflen % device->fraglen;
272 /* sanity */
273 if(overshot)
275 overshot -= overshot % device->pwfx->nBlockAlign;
276 device->pwave[device->helfrags - 1].dwBufferLength += overshot;
279 TRACE("fraglen=%d, overshot=%d\n", device->fraglen, overshot);
281 device->mixfunction = mixfunctions[device->pwfx->wBitsPerSample/8 - 1];
282 device->normfunction = normfunctions[device->pwfx->wBitsPerSample/8 - 1];
283 FillMemory(device->buffer, device->buflen, (device->pwfx->wBitsPerSample == 8) ? 128 : 0);
284 FillMemory(device->mix_buffer, device->mix_buffer_len, 0);
285 device->pwplay = device->pwqueue = device->playpos = device->mixpos = 0;
286 return err;
290 static void DSOUND_PrimaryClose(DirectSoundDevice *device)
292 TRACE("(%p)\n", device);
294 /* are we using waveOut stuff? */
295 if (!device->hwbuf) {
296 unsigned c;
298 /* get out of CS when calling the wave system */
299 LeaveCriticalSection(&(device->mixlock));
300 /* **** */
301 device->pwqueue = (DWORD)-1; /* resetting queues */
302 waveOutReset(device->hwo);
303 for (c=0; c<device->helfrags; c++)
304 waveOutUnprepareHeader(device->hwo, &device->pwave[c], sizeof(WAVEHDR));
305 /* **** */
306 EnterCriticalSection(&(device->mixlock));
308 /* clear the queue */
309 device->pwqueue = 0;
310 } else {
311 ULONG ref = IDsDriverBuffer_Release(device->hwbuf);
312 if (!ref)
313 device->hwbuf = 0;
314 else
315 ERR("Still %d references on primary buffer, refcount leak?\n", ref);
319 HRESULT DSOUND_PrimaryCreate(DirectSoundDevice *device)
321 HRESULT err = DS_OK;
322 TRACE("(%p)\n", device);
324 device->buflen = ds_hel_buflen;
325 err = DSOUND_PrimaryOpen(device);
327 if (err != DS_OK) {
328 WARN("DSOUND_PrimaryOpen failed\n");
329 return err;
332 device->state = STATE_STOPPED;
333 return DS_OK;
336 HRESULT DSOUND_PrimaryDestroy(DirectSoundDevice *device)
338 TRACE("(%p)\n", device);
340 /* **** */
341 EnterCriticalSection(&(device->mixlock));
343 DSOUND_PrimaryClose(device);
344 if (device->driver) {
345 if (device->hwbuf) {
346 if (IDsDriverBuffer_Release(device->hwbuf) == 0)
347 device->hwbuf = 0;
349 } else
350 HeapFree(GetProcessHeap(),0,device->pwave);
351 HeapFree(GetProcessHeap(),0,device->pwfx);
352 device->pwfx=NULL;
354 LeaveCriticalSection(&(device->mixlock));
355 /* **** */
357 return DS_OK;
360 HRESULT DSOUND_PrimaryPlay(DirectSoundDevice *device)
362 HRESULT err = DS_OK;
363 TRACE("(%p)\n", device);
365 if (device->hwbuf) {
366 err = IDsDriverBuffer_Play(device->hwbuf, 0, 0, DSBPLAY_LOOPING);
367 if (err != DS_OK)
368 WARN("IDsDriverBuffer_Play failed\n");
369 } else {
370 err = mmErr(waveOutRestart(device->hwo));
371 if (err != DS_OK)
372 WARN("waveOutRestart failed\n");
375 return err;
378 HRESULT DSOUND_PrimaryStop(DirectSoundDevice *device)
380 HRESULT err = DS_OK;
381 TRACE("(%p)\n", device);
383 if (device->hwbuf) {
384 err = IDsDriverBuffer_Stop(device->hwbuf);
385 if (err == DSERR_BUFFERLOST) {
386 DSOUND_PrimaryClose(device);
387 err = DSOUND_ReopenDevice(device, FALSE);
388 if (FAILED(err))
389 ERR("DSOUND_ReopenDevice failed\n");
390 else
392 err = DSOUND_PrimaryOpen(device);
393 if (FAILED(err))
394 WARN("DSOUND_PrimaryOpen failed\n");
396 } else if (err != DS_OK) {
397 WARN("IDsDriverBuffer_Stop failed\n");
399 } else {
401 /* don't call the wave system with the lock set */
402 LeaveCriticalSection(&(device->mixlock));
403 /* **** */
405 err = mmErr(waveOutPause(device->hwo));
407 /* **** */
408 EnterCriticalSection(&(device->mixlock));
410 if (err != DS_OK)
411 WARN("waveOutPause failed\n");
414 return err;
417 HRESULT DSOUND_PrimaryGetPosition(DirectSoundDevice *device, LPDWORD playpos, LPDWORD writepos)
419 TRACE("(%p,%p,%p)\n", device, playpos, writepos);
421 if (device->hwbuf) {
422 HRESULT err=IDsDriverBuffer_GetPosition(device->hwbuf,playpos,writepos);
423 if (err != S_OK) {
424 WARN("IDsDriverBuffer_GetPosition failed\n");
425 return err;
427 } else {
428 TRACE("pwplay=%i, pwqueue=%i\n", device->pwplay, device->pwqueue);
430 /* check if playpos was requested */
431 if (playpos)
432 /* use the cached play position */
433 *playpos = device->pwplay * device->fraglen;
435 /* check if writepos was requested */
436 if (writepos)
437 /* the writepos is the first non-queued position */
438 *writepos = ((device->pwplay + device->pwqueue) % device->helfrags) * device->fraglen;
440 TRACE("playpos = %d, writepos = %d (%p, time=%d)\n", playpos?*playpos:-1, writepos?*writepos:-1, device, GetTickCount());
441 return DS_OK;
444 LPWAVEFORMATEX DSOUND_CopyFormat(LPCWAVEFORMATEX wfex)
446 DWORD size = wfex->wFormatTag == WAVE_FORMAT_PCM ?
447 sizeof(WAVEFORMATEX) : sizeof(WAVEFORMATEX) + wfex->cbSize;
448 LPWAVEFORMATEX pwfx = HeapAlloc(GetProcessHeap(),0,size);
449 if (pwfx == NULL) {
450 WARN("out of memory\n");
451 } else if (wfex->wFormatTag != WAVE_FORMAT_PCM) {
452 CopyMemory(pwfx, wfex, size);
453 } else {
454 CopyMemory(pwfx, wfex, sizeof(PCMWAVEFORMAT));
455 pwfx->cbSize=0;
456 if (pwfx->nBlockAlign != pwfx->nChannels * pwfx->wBitsPerSample/8) {
457 WARN("Fixing bad nBlockAlign (%u)\n", pwfx->nBlockAlign);
458 pwfx->nBlockAlign = pwfx->nChannels * pwfx->wBitsPerSample/8;
460 if (pwfx->nAvgBytesPerSec != pwfx->nSamplesPerSec * pwfx->nBlockAlign) {
461 WARN("Fixing bad nAvgBytesPerSec (%u)\n", pwfx->nAvgBytesPerSec);
462 pwfx->nAvgBytesPerSec = pwfx->nSamplesPerSec * pwfx->nBlockAlign;
465 return pwfx;
468 static HRESULT DSOUND_PrimarySetFormat(DirectSoundDevice *device, LPCWAVEFORMATEX wfex, BOOL forced)
470 HRESULT err = DSERR_BUFFERLOST;
471 int i;
472 DWORD nSamplesPerSec, bpp, chans;
473 LPWAVEFORMATEX oldpwfx;
474 TRACE("(%p,%p)\n", device, wfex);
476 if (device->priolevel == DSSCL_NORMAL) {
477 WARN("failed priority check!\n");
478 return DSERR_PRIOLEVELNEEDED;
481 /* Let's be pedantic! */
482 if (wfex == NULL) {
483 WARN("invalid parameter: wfex==NULL!\n");
484 return DSERR_INVALIDPARAM;
486 TRACE("(formattag=0x%04x,chans=%d,samplerate=%d,"
487 "bytespersec=%d,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
488 wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
489 wfex->nAvgBytesPerSec, wfex->nBlockAlign,
490 wfex->wBitsPerSample, wfex->cbSize);
492 /* **** */
493 RtlAcquireResourceExclusive(&(device->buffer_list_lock), TRUE);
494 EnterCriticalSection(&(device->mixlock));
496 nSamplesPerSec = device->pwfx->nSamplesPerSec;
497 bpp = device->pwfx->wBitsPerSample;
498 chans = device->pwfx->nChannels;
500 oldpwfx = device->pwfx;
501 device->pwfx = DSOUND_CopyFormat(wfex);
502 if (device->pwfx == NULL) {
503 device->pwfx = oldpwfx;
504 err = DSERR_OUTOFMEMORY;
505 goto done;
507 /* TODO: on failure below (bad format?), reinstall oldpwfx */
508 HeapFree(GetProcessHeap(), 0, oldpwfx);
510 if (!(device->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMSETFORMAT) && device->hwbuf) {
511 err = IDsDriverBuffer_SetFormat(device->hwbuf, device->pwfx);
513 /* On bad format, try to re-create, big chance it will work then, only do this if we <HAVE> to */
514 if (forced && (device->pwfx->nSamplesPerSec/100 != wfex->nSamplesPerSec/100 || err == DSERR_BADFORMAT))
516 DWORD cp_size = wfex->wFormatTag == WAVE_FORMAT_PCM ?
517 sizeof(PCMWAVEFORMAT) : sizeof(WAVEFORMATEX) + wfex->cbSize;
518 err = DSERR_BUFFERLOST;
519 CopyMemory(device->pwfx, wfex, cp_size);
522 if (err != DSERR_BUFFERLOST && FAILED(err)) {
523 WARN("IDsDriverBuffer_SetFormat failed\n");
524 if (!forced)
525 err = DS_OK;
526 goto done;
529 if (err == S_FALSE)
531 /* ALSA specific: S_FALSE tells that recreation was successful,
532 * but size and location may be changed, and buffer has to be restarted
533 * I put it here, so if frequency doesn't match the error will be changed to DSERR_BUFFERLOST
534 * and the entire re-initialization will occur anyway
536 IDsDriverBuffer_Lock(device->hwbuf, (LPVOID *)&device->buffer, &device->buflen, NULL, NULL, 0, 0, DSBLOCK_ENTIREBUFFER);
537 IDsDriverBuffer_Unlock(device->hwbuf, device->buffer, 0, NULL, 0);
539 if (device->state == STATE_PLAYING) device->state = STATE_STARTING;
540 else if (device->state == STATE_STOPPING) device->state = STATE_STOPPED;
541 device->pwplay = device->pwqueue = device->playpos = device->mixpos = 0;
542 err = DS_OK;
544 DSOUND_RecalcPrimary(device);
547 if (err == DSERR_BUFFERLOST)
549 DSOUND_PrimaryClose(device);
551 err = DSOUND_ReopenDevice(device, FALSE);
552 if (FAILED(err))
554 WARN("DSOUND_ReopenDevice failed: %08x\n", err);
555 goto done;
557 err = DSOUND_PrimaryOpen(device);
558 if (err != DS_OK) {
559 WARN("DSOUND_PrimaryOpen failed\n");
560 goto done;
563 if (wfex->nSamplesPerSec/100 != device->pwfx->nSamplesPerSec/100 && forced && device->buffer)
565 DSOUND_PrimaryClose(device);
566 device->pwfx->nSamplesPerSec = wfex->nSamplesPerSec;
567 err = DSOUND_ReopenDevice(device, TRUE);
568 if (FAILED(err))
569 WARN("DSOUND_ReopenDevice(2) failed: %08x\n", err);
570 else if (FAILED((err = DSOUND_PrimaryOpen(device))))
571 WARN("DSOUND_PrimaryOpen(2) failed: %08x\n", err);
575 device->mix_buffer_len = DSOUND_bufpos_to_mixpos(device, device->buflen);
576 device->mix_buffer = HeapReAlloc(GetProcessHeap(), 0, device->mix_buffer, device->mix_buffer_len);
577 FillMemory(device->mix_buffer, device->mix_buffer_len, 0);
578 device->mixfunction = mixfunctions[device->pwfx->wBitsPerSample/8 - 1];
579 device->normfunction = normfunctions[device->pwfx->wBitsPerSample/8 - 1];
581 if (nSamplesPerSec != device->pwfx->nSamplesPerSec || bpp != device->pwfx->wBitsPerSample || chans != device->pwfx->nChannels) {
582 IDirectSoundBufferImpl** dsb = device->buffers;
583 for (i = 0; i < device->nrofbuffers; i++, dsb++) {
584 /* **** */
585 RtlAcquireResourceExclusive(&(*dsb)->lock, TRUE);
587 (*dsb)->freqAdjust = ((DWORD64)(*dsb)->freq << DSOUND_FREQSHIFT) / device->pwfx->nSamplesPerSec;
588 DSOUND_RecalcFormat((*dsb));
589 DSOUND_MixToTemporary((*dsb), 0, (*dsb)->buflen, FALSE);
590 (*dsb)->primary_mixpos = 0;
592 RtlReleaseResource(&(*dsb)->lock);
593 /* **** */
597 done:
598 LeaveCriticalSection(&(device->mixlock));
599 RtlReleaseResource(&(device->buffer_list_lock));
600 /* **** */
602 return err;
605 /*******************************************************************************
606 * PrimaryBuffer
608 /* This sets this format for the <em>Primary Buffer Only</em> */
609 /* See file:///cdrom/sdk52/docs/worddoc/dsound.doc page 120 */
610 static HRESULT WINAPI PrimaryBufferImpl_SetFormat(
611 LPDIRECTSOUNDBUFFER iface,
612 LPCWAVEFORMATEX wfex)
614 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
615 TRACE("(%p,%p)\n", iface, wfex);
616 return DSOUND_PrimarySetFormat(device, wfex, device->priolevel == DSSCL_WRITEPRIMARY);
619 static HRESULT WINAPI PrimaryBufferImpl_SetVolume(
620 LPDIRECTSOUNDBUFFER iface,LONG vol
622 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
623 DWORD ampfactors;
624 HRESULT hres = DS_OK;
625 TRACE("(%p,%d)\n", iface, vol);
627 if (!(device->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
628 WARN("control unavailable\n");
629 return DSERR_CONTROLUNAVAIL;
632 if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN)) {
633 WARN("invalid parameter: vol = %d\n", vol);
634 return DSERR_INVALIDPARAM;
637 /* **** */
638 EnterCriticalSection(&(device->mixlock));
640 waveOutGetVolume(device->hwo, &ampfactors);
641 device->volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
642 device->volpan.dwTotalRightAmpFactor=ampfactors >> 16;
643 DSOUND_AmpFactorToVolPan(&device->volpan);
644 if (vol != device->volpan.lVolume) {
645 device->volpan.lVolume=vol;
646 DSOUND_RecalcVolPan(&device->volpan);
647 if (device->hwbuf) {
648 hres = IDsDriverBuffer_SetVolumePan(device->hwbuf, &device->volpan);
649 if (hres != DS_OK)
650 WARN("IDsDriverBuffer_SetVolumePan failed\n");
651 } else {
652 ampfactors = (device->volpan.dwTotalLeftAmpFactor & 0xffff) | (device->volpan.dwTotalRightAmpFactor << 16);
653 waveOutSetVolume(device->hwo, ampfactors);
657 LeaveCriticalSection(&(device->mixlock));
658 /* **** */
660 return hres;
663 static HRESULT WINAPI PrimaryBufferImpl_GetVolume(
664 LPDIRECTSOUNDBUFFER iface,LPLONG vol
666 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
667 DWORD ampfactors;
668 TRACE("(%p,%p)\n", iface, vol);
670 if (!(device->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
671 WARN("control unavailable\n");
672 return DSERR_CONTROLUNAVAIL;
675 if (vol == NULL) {
676 WARN("invalid parameter: vol = NULL\n");
677 return DSERR_INVALIDPARAM;
680 if (!device->hwbuf)
682 waveOutGetVolume(device->hwo, &ampfactors);
683 device->volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
684 device->volpan.dwTotalRightAmpFactor=ampfactors >> 16;
685 DSOUND_AmpFactorToVolPan(&device->volpan);
687 *vol = device->volpan.lVolume;
688 return DS_OK;
691 static HRESULT WINAPI PrimaryBufferImpl_SetFrequency(
692 LPDIRECTSOUNDBUFFER iface,DWORD freq
694 PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
695 TRACE("(%p,%d)\n",This,freq);
697 /* You cannot set the frequency of the primary buffer */
698 WARN("control unavailable\n");
699 return DSERR_CONTROLUNAVAIL;
702 static HRESULT WINAPI PrimaryBufferImpl_Play(
703 LPDIRECTSOUNDBUFFER iface,DWORD reserved1,DWORD reserved2,DWORD flags
705 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
706 TRACE("(%p,%08x,%08x,%08x)\n", iface, reserved1, reserved2, flags);
708 if (!(flags & DSBPLAY_LOOPING)) {
709 WARN("invalid parameter: flags = %08x\n", flags);
710 return DSERR_INVALIDPARAM;
713 /* **** */
714 EnterCriticalSection(&(device->mixlock));
716 if (device->state == STATE_STOPPED)
717 device->state = STATE_STARTING;
718 else if (device->state == STATE_STOPPING)
719 device->state = STATE_PLAYING;
721 LeaveCriticalSection(&(device->mixlock));
722 /* **** */
724 return DS_OK;
727 static HRESULT WINAPI PrimaryBufferImpl_Stop(LPDIRECTSOUNDBUFFER iface)
729 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
730 TRACE("(%p)\n", iface);
732 /* **** */
733 EnterCriticalSection(&(device->mixlock));
735 if (device->state == STATE_PLAYING)
736 device->state = STATE_STOPPING;
737 else if (device->state == STATE_STARTING)
738 device->state = STATE_STOPPED;
740 LeaveCriticalSection(&(device->mixlock));
741 /* **** */
743 return DS_OK;
746 static ULONG WINAPI PrimaryBufferImpl_AddRef(LPDIRECTSOUNDBUFFER iface)
748 PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
749 ULONG ref = InterlockedIncrement(&(This->ref));
750 TRACE("(%p) ref was %d\n", This, ref - 1);
751 return ref;
754 static ULONG WINAPI PrimaryBufferImpl_Release(LPDIRECTSOUNDBUFFER iface)
756 PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
757 DWORD ref = InterlockedDecrement(&(This->ref));
758 TRACE("(%p) ref was %d\n", This, ref + 1);
760 if (!ref) {
761 This->device->primary = NULL;
762 HeapFree(GetProcessHeap(), 0, This);
763 TRACE("(%p) released\n", This);
765 return ref;
768 static HRESULT WINAPI PrimaryBufferImpl_GetCurrentPosition(
769 LPDIRECTSOUNDBUFFER iface,LPDWORD playpos,LPDWORD writepos
771 HRESULT hres;
772 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
773 TRACE("(%p,%p,%p)\n", iface, playpos, writepos);
775 /* **** */
776 EnterCriticalSection(&(device->mixlock));
778 hres = DSOUND_PrimaryGetPosition(device, playpos, writepos);
779 if (hres != DS_OK) {
780 WARN("DSOUND_PrimaryGetPosition failed\n");
781 LeaveCriticalSection(&(device->mixlock));
782 return hres;
784 if (writepos) {
785 if (device->state != STATE_STOPPED)
786 /* apply the documented 10ms lead to writepos */
787 *writepos += device->writelead;
788 while (*writepos >= device->buflen) *writepos -= device->buflen;
791 LeaveCriticalSection(&(device->mixlock));
792 /* **** */
794 TRACE("playpos = %d, writepos = %d (%p, time=%d)\n", playpos?*playpos:0, writepos?*writepos:0, device, GetTickCount());
795 return DS_OK;
798 static HRESULT WINAPI PrimaryBufferImpl_GetStatus(
799 LPDIRECTSOUNDBUFFER iface,LPDWORD status
801 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
802 TRACE("(%p,%p)\n", iface, status);
804 if (status == NULL) {
805 WARN("invalid parameter: status == NULL\n");
806 return DSERR_INVALIDPARAM;
809 *status = 0;
810 if ((device->state == STATE_STARTING) ||
811 (device->state == STATE_PLAYING))
812 *status |= DSBSTATUS_PLAYING | DSBSTATUS_LOOPING;
814 TRACE("status=%x\n", *status);
815 return DS_OK;
819 static HRESULT WINAPI PrimaryBufferImpl_GetFormat(
820 LPDIRECTSOUNDBUFFER iface,
821 LPWAVEFORMATEX lpwf,
822 DWORD wfsize,
823 LPDWORD wfwritten)
825 DWORD size;
826 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
827 TRACE("(%p,%p,%d,%p)\n", iface, lpwf, wfsize, wfwritten);
829 size = sizeof(WAVEFORMATEX) + device->pwfx->cbSize;
831 if (lpwf) { /* NULL is valid */
832 if (wfsize >= size) {
833 CopyMemory(lpwf,device->pwfx,size);
834 if (wfwritten)
835 *wfwritten = size;
836 } else {
837 WARN("invalid parameter: wfsize too small\n");
838 if (wfwritten)
839 *wfwritten = 0;
840 return DSERR_INVALIDPARAM;
842 } else {
843 if (wfwritten)
844 *wfwritten = sizeof(WAVEFORMATEX) + device->pwfx->cbSize;
845 else {
846 WARN("invalid parameter: wfwritten == NULL\n");
847 return DSERR_INVALIDPARAM;
851 return DS_OK;
854 static HRESULT WINAPI PrimaryBufferImpl_Lock(
855 LPDIRECTSOUNDBUFFER iface,DWORD writecursor,DWORD writebytes,LPVOID *lplpaudioptr1,LPDWORD audiobytes1,LPVOID *lplpaudioptr2,LPDWORD audiobytes2,DWORD flags
857 HRESULT hres;
858 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
859 TRACE("(%p,%d,%d,%p,%p,%p,%p,0x%08x) at %d\n",
860 iface,
861 writecursor,
862 writebytes,
863 lplpaudioptr1,
864 audiobytes1,
865 lplpaudioptr2,
866 audiobytes2,
867 flags,
868 GetTickCount()
871 if (!audiobytes1)
872 return DSERR_INVALIDPARAM;
874 if (device->priolevel != DSSCL_WRITEPRIMARY) {
875 WARN("failed priority check!\n");
876 return DSERR_PRIOLEVELNEEDED;
879 /* when this flag is set, writecursor is meaningless and must be calculated */
880 if (flags & DSBLOCK_FROMWRITECURSOR) {
881 /* GetCurrentPosition does too much magic to duplicate here */
882 hres = IDirectSoundBuffer_GetCurrentPosition(iface, NULL, &writecursor);
883 if (hres != DS_OK) {
884 WARN("IDirectSoundBuffer_GetCurrentPosition failed\n");
885 return hres;
889 /* when this flag is set, writebytes is meaningless and must be set */
890 if (flags & DSBLOCK_ENTIREBUFFER)
891 writebytes = device->buflen;
893 if (writecursor >= device->buflen) {
894 WARN("Invalid parameter, writecursor: %u >= buflen: %u\n",
895 writecursor, device->buflen);
896 return DSERR_INVALIDPARAM;
899 if (writebytes > device->buflen) {
900 WARN("Invalid parameter, writebytes: %u > buflen: %u\n",
901 writebytes, device->buflen);
902 return DSERR_INVALIDPARAM;
905 if (!(device->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK) && device->hwbuf) {
906 hres = IDsDriverBuffer_Lock(device->hwbuf,
907 lplpaudioptr1, audiobytes1,
908 lplpaudioptr2, audiobytes2,
909 writecursor, writebytes,
911 if (hres != DS_OK) {
912 WARN("IDsDriverBuffer_Lock failed\n");
913 return hres;
915 } else {
916 if (writecursor+writebytes <= device->buflen) {
917 *(LPBYTE*)lplpaudioptr1 = device->buffer+writecursor;
918 *audiobytes1 = writebytes;
919 if (lplpaudioptr2)
920 *(LPBYTE*)lplpaudioptr2 = NULL;
921 if (audiobytes2)
922 *audiobytes2 = 0;
923 TRACE("->%d.0\n",writebytes);
924 } else {
925 *(LPBYTE*)lplpaudioptr1 = device->buffer+writecursor;
926 *audiobytes1 = device->buflen-writecursor;
927 if (lplpaudioptr2)
928 *(LPBYTE*)lplpaudioptr2 = device->buffer;
929 if (audiobytes2)
930 *audiobytes2 = writebytes-(device->buflen-writecursor);
931 TRACE("->%d.%d\n",*audiobytes1,audiobytes2?*audiobytes2:0);
934 return DS_OK;
937 static HRESULT WINAPI PrimaryBufferImpl_SetCurrentPosition(
938 LPDIRECTSOUNDBUFFER iface,DWORD newpos
940 PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
941 TRACE("(%p,%d)\n",This,newpos);
943 /* You cannot set the position of the primary buffer */
944 WARN("invalid call\n");
945 return DSERR_INVALIDCALL;
948 static HRESULT WINAPI PrimaryBufferImpl_SetPan(
949 LPDIRECTSOUNDBUFFER iface,LONG pan
951 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
952 DWORD ampfactors;
953 HRESULT hres = DS_OK;
954 TRACE("(%p,%d)\n", iface, pan);
956 if (!(device->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
957 WARN("control unavailable\n");
958 return DSERR_CONTROLUNAVAIL;
961 if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT)) {
962 WARN("invalid parameter: pan = %d\n", pan);
963 return DSERR_INVALIDPARAM;
966 /* **** */
967 EnterCriticalSection(&(device->mixlock));
969 if (!device->hwbuf)
971 waveOutGetVolume(device->hwo, &ampfactors);
972 device->volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
973 device->volpan.dwTotalRightAmpFactor=ampfactors >> 16;
974 DSOUND_AmpFactorToVolPan(&device->volpan);
976 if (pan != device->volpan.lPan) {
977 device->volpan.lPan=pan;
978 DSOUND_RecalcVolPan(&device->volpan);
979 if (device->hwbuf) {
980 hres = IDsDriverBuffer_SetVolumePan(device->hwbuf, &device->volpan);
981 if (hres != DS_OK)
982 WARN("IDsDriverBuffer_SetVolumePan failed\n");
983 } else {
984 ampfactors = (device->volpan.dwTotalLeftAmpFactor & 0xffff) | (device->volpan.dwTotalRightAmpFactor << 16);
985 waveOutSetVolume(device->hwo, ampfactors);
989 LeaveCriticalSection(&(device->mixlock));
990 /* **** */
992 return hres;
995 static HRESULT WINAPI PrimaryBufferImpl_GetPan(
996 LPDIRECTSOUNDBUFFER iface,LPLONG pan
998 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
999 DWORD ampfactors;
1000 TRACE("(%p,%p)\n", iface, pan);
1002 if (!(device->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
1003 WARN("control unavailable\n");
1004 return DSERR_CONTROLUNAVAIL;
1007 if (pan == NULL) {
1008 WARN("invalid parameter: pan == NULL\n");
1009 return DSERR_INVALIDPARAM;
1012 if (!device->hwbuf)
1014 waveOutGetVolume(device->hwo, &ampfactors);
1015 device->volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
1016 device->volpan.dwTotalRightAmpFactor=ampfactors >> 16;
1017 DSOUND_AmpFactorToVolPan(&device->volpan);
1019 *pan = device->volpan.lPan;
1020 return DS_OK;
1023 static HRESULT WINAPI PrimaryBufferImpl_Unlock(
1024 LPDIRECTSOUNDBUFFER iface,LPVOID p1,DWORD x1,LPVOID p2,DWORD x2
1026 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
1027 TRACE("(%p,%p,%d,%p,%d)\n", iface, p1, x1, p2, x2);
1029 if (device->priolevel != DSSCL_WRITEPRIMARY) {
1030 WARN("failed priority check!\n");
1031 return DSERR_PRIOLEVELNEEDED;
1034 if (!(device->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK) && device->hwbuf) {
1035 HRESULT hres;
1037 if ((char *)p1 - (char *)device->buffer + x1 > device->buflen)
1038 hres = DSERR_INVALIDPARAM;
1039 else
1040 hres = IDsDriverBuffer_Unlock(device->hwbuf, p1, x1, p2, x2);
1042 if (hres != DS_OK) {
1043 WARN("IDsDriverBuffer_Unlock failed\n");
1044 return hres;
1048 return DS_OK;
1051 static HRESULT WINAPI PrimaryBufferImpl_Restore(
1052 LPDIRECTSOUNDBUFFER iface
1054 PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
1055 FIXME("(%p):stub\n",This);
1056 return DS_OK;
1059 static HRESULT WINAPI PrimaryBufferImpl_GetFrequency(
1060 LPDIRECTSOUNDBUFFER iface,LPDWORD freq
1062 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
1063 TRACE("(%p,%p)\n", iface, freq);
1065 if (freq == NULL) {
1066 WARN("invalid parameter: freq == NULL\n");
1067 return DSERR_INVALIDPARAM;
1070 if (!(device->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) {
1071 WARN("control unavailable\n");
1072 return DSERR_CONTROLUNAVAIL;
1075 *freq = device->pwfx->nSamplesPerSec;
1076 TRACE("-> %d\n", *freq);
1078 return DS_OK;
1081 static HRESULT WINAPI PrimaryBufferImpl_Initialize(
1082 LPDIRECTSOUNDBUFFER iface,LPDIRECTSOUND dsound,LPCDSBUFFERDESC dbsd
1084 PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
1085 WARN("(%p) already initialized\n", This);
1086 return DSERR_ALREADYINITIALIZED;
1089 static HRESULT WINAPI PrimaryBufferImpl_GetCaps(
1090 LPDIRECTSOUNDBUFFER iface,LPDSBCAPS caps
1092 DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
1093 TRACE("(%p,%p)\n", iface, caps);
1095 if (caps == NULL) {
1096 WARN("invalid parameter: caps == NULL\n");
1097 return DSERR_INVALIDPARAM;
1100 if (caps->dwSize < sizeof(*caps)) {
1101 WARN("invalid parameter: caps->dwSize = %d\n", caps->dwSize);
1102 return DSERR_INVALIDPARAM;
1105 caps->dwFlags = device->dsbd.dwFlags;
1106 caps->dwBufferBytes = device->buflen;
1108 /* Windows reports these as zero */
1109 caps->dwUnlockTransferRate = 0;
1110 caps->dwPlayCpuOverhead = 0;
1112 return DS_OK;
1115 static HRESULT WINAPI PrimaryBufferImpl_QueryInterface(
1116 LPDIRECTSOUNDBUFFER iface,REFIID riid,LPVOID *ppobj
1118 PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
1119 DirectSoundDevice *device = This->device;
1120 TRACE("(%p,%s,%p)\n", iface, debugstr_guid(riid), ppobj);
1122 if (ppobj == NULL) {
1123 WARN("invalid parameter\n");
1124 return E_INVALIDARG;
1127 *ppobj = NULL; /* assume failure */
1129 if ( IsEqualGUID(riid, &IID_IUnknown) ||
1130 IsEqualGUID(riid, &IID_IDirectSoundBuffer) ) {
1131 IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)This);
1132 *ppobj = This;
1133 return S_OK;
1136 /* DirectSoundBuffer and DirectSoundBuffer8 are different and */
1137 /* a primary buffer can't have a DirectSoundBuffer8 interface */
1138 if ( IsEqualGUID( &IID_IDirectSoundBuffer8, riid ) ) {
1139 WARN("app requested DirectSoundBuffer8 on primary buffer\n");
1140 return E_NOINTERFACE;
1143 if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
1144 ERR("app requested IDirectSoundNotify on primary buffer\n");
1145 /* FIXME: should we support this? */
1146 return E_NOINTERFACE;
1149 if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
1150 ERR("app requested IDirectSound3DBuffer on primary buffer\n");
1151 return E_NOINTERFACE;
1154 if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
1155 if (!device->listener)
1156 IDirectSound3DListenerImpl_Create(device, &device->listener);
1157 if (device->listener) {
1158 *ppobj = device->listener;
1159 IDirectSound3DListener_AddRef((LPDIRECTSOUND3DLISTENER)*ppobj);
1160 return S_OK;
1163 WARN("IID_IDirectSound3DListener failed\n");
1164 return E_NOINTERFACE;
1167 if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
1168 FIXME("app requested IKsPropertySet on primary buffer\n");
1169 return E_NOINTERFACE;
1172 FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
1173 return E_NOINTERFACE;
1176 static const IDirectSoundBufferVtbl dspbvt =
1178 PrimaryBufferImpl_QueryInterface,
1179 PrimaryBufferImpl_AddRef,
1180 PrimaryBufferImpl_Release,
1181 PrimaryBufferImpl_GetCaps,
1182 PrimaryBufferImpl_GetCurrentPosition,
1183 PrimaryBufferImpl_GetFormat,
1184 PrimaryBufferImpl_GetVolume,
1185 PrimaryBufferImpl_GetPan,
1186 PrimaryBufferImpl_GetFrequency,
1187 PrimaryBufferImpl_GetStatus,
1188 PrimaryBufferImpl_Initialize,
1189 PrimaryBufferImpl_Lock,
1190 PrimaryBufferImpl_Play,
1191 PrimaryBufferImpl_SetCurrentPosition,
1192 PrimaryBufferImpl_SetFormat,
1193 PrimaryBufferImpl_SetVolume,
1194 PrimaryBufferImpl_SetPan,
1195 PrimaryBufferImpl_SetFrequency,
1196 PrimaryBufferImpl_Stop,
1197 PrimaryBufferImpl_Unlock,
1198 PrimaryBufferImpl_Restore
1201 HRESULT PrimaryBufferImpl_Create(
1202 DirectSoundDevice * device,
1203 PrimaryBufferImpl ** ppdsb,
1204 LPCDSBUFFERDESC dsbd)
1206 PrimaryBufferImpl *dsb;
1207 TRACE("%p,%p,%p)\n",device,ppdsb,dsbd);
1209 if (dsbd->lpwfxFormat) {
1210 WARN("invalid parameter: dsbd->lpwfxFormat != NULL\n");
1211 *ppdsb = NULL;
1212 return DSERR_INVALIDPARAM;
1215 dsb = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*dsb));
1217 if (dsb == NULL) {
1218 WARN("out of memory\n");
1219 *ppdsb = NULL;
1220 return DSERR_OUTOFMEMORY;
1223 dsb->ref = 0;
1224 dsb->device = device;
1225 dsb->lpVtbl = &dspbvt;
1227 device->dsbd = *dsbd;
1229 TRACE("Created primary buffer at %p\n", dsb);
1230 TRACE("(formattag=0x%04x,chans=%d,samplerate=%d,"
1231 "bytespersec=%d,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
1232 device->pwfx->wFormatTag, device->pwfx->nChannels,
1233 device->pwfx->nSamplesPerSec, device->pwfx->nAvgBytesPerSec,
1234 device->pwfx->nBlockAlign, device->pwfx->wBitsPerSample,
1235 device->pwfx->cbSize);
1237 *ppdsb = dsb;
1238 return S_OK;