imm32: Ignore some messages in ImmTranslateMessage.
[wine.git] / dlls / dsound / primary.c
blob55f9ea94f907fd7b5684ac89709b08f479d6f4e3
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 COBJMACROS
29 #define NONAMELESSUNION
31 #include "windef.h"
32 #include "winbase.h"
33 #include "winuser.h"
34 #include "mmsystem.h"
35 #include "mmddk.h"
36 #include "wine/debug.h"
37 #include "dsound.h"
38 #include "dsound_private.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
42 static DWORD speaker_config_to_channel_mask(DWORD speaker_config)
44 switch (DSSPEAKER_CONFIG(speaker_config)) {
45 case DSSPEAKER_MONO:
46 return SPEAKER_FRONT_LEFT;
48 case DSSPEAKER_STEREO:
49 case DSSPEAKER_HEADPHONE:
50 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
52 case DSSPEAKER_QUAD:
53 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT;
55 case DSSPEAKER_5POINT1_BACK:
56 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT;
59 WARN("unknown speaker_config %lu\n", speaker_config);
60 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
63 static DWORD DSOUND_FindSpeakerConfig(IMMDevice *mmdevice, int channels)
65 IPropertyStore *store;
66 HRESULT hr;
67 PROPVARIANT pv;
68 ULONG phys_speakers;
70 const DWORD def = DSSPEAKER_COMBINED(DSSPEAKER_STEREO, DSSPEAKER_GEOMETRY_WIDE);
72 hr = IMMDevice_OpenPropertyStore(mmdevice, STGM_READ, &store);
73 if (FAILED(hr)) {
74 WARN("IMMDevice_OpenPropertyStore failed: %08lx\n", hr);
75 return def;
78 hr = IPropertyStore_GetValue(store, &PKEY_AudioEndpoint_PhysicalSpeakers, &pv);
80 if (FAILED(hr)) {
81 WARN("IPropertyStore_GetValue failed: %08lx\n", hr);
82 IPropertyStore_Release(store);
83 return def;
86 if (pv.vt != VT_UI4) {
87 WARN("PKEY_AudioEndpoint_PhysicalSpeakers is not a ULONG: 0x%x\n", pv.vt);
88 PropVariantClear(&pv);
89 IPropertyStore_Release(store);
90 return def;
93 phys_speakers = pv.ulVal;
95 PropVariantClear(&pv);
96 IPropertyStore_Release(store);
98 if ((channels >= 6 || channels == 0) && (phys_speakers & KSAUDIO_SPEAKER_5POINT1) == KSAUDIO_SPEAKER_5POINT1)
99 return DSSPEAKER_5POINT1_BACK;
100 else if ((channels >= 6 || channels == 0) && (phys_speakers & KSAUDIO_SPEAKER_5POINT1_SURROUND) == KSAUDIO_SPEAKER_5POINT1_SURROUND)
101 return DSSPEAKER_5POINT1_SURROUND;
102 else if ((channels >= 4 || channels == 0) && (phys_speakers & KSAUDIO_SPEAKER_QUAD) == KSAUDIO_SPEAKER_QUAD)
103 return DSSPEAKER_QUAD;
104 else if ((channels >= 2 || channels == 0) && (phys_speakers & KSAUDIO_SPEAKER_STEREO) == KSAUDIO_SPEAKER_STEREO)
105 return DSSPEAKER_COMBINED(DSSPEAKER_STEREO, DSSPEAKER_GEOMETRY_WIDE);
106 else if ((phys_speakers & KSAUDIO_SPEAKER_MONO) == KSAUDIO_SPEAKER_MONO)
107 return DSSPEAKER_MONO;
109 return def;
112 static HRESULT DSOUND_WaveFormat(DirectSoundDevice *device, IAudioClient *client,
113 BOOL forcewave, WAVEFORMATEX **wfx)
115 WAVEFORMATEXTENSIBLE *retwfe = NULL;
116 WAVEFORMATEX *w;
117 HRESULT hr;
119 if (!forcewave) {
120 WAVEFORMATEXTENSIBLE *mixwfe;
121 hr = IAudioClient_GetMixFormat(client, (WAVEFORMATEX**)&mixwfe);
123 if (FAILED(hr))
124 return hr;
126 if (mixwfe->Format.nChannels < device->num_speakers) {
127 device->speaker_config = DSOUND_FindSpeakerConfig(device->mmdevice, mixwfe->Format.nChannels);
128 DSOUND_ParseSpeakerConfig(device);
129 } else if (mixwfe->Format.nChannels > device->num_speakers) {
130 mixwfe->Format.nChannels = device->num_speakers;
131 mixwfe->Format.nBlockAlign = mixwfe->Format.nChannels * mixwfe->Format.wBitsPerSample / 8;
132 mixwfe->Format.nAvgBytesPerSec = mixwfe->Format.nSamplesPerSec * mixwfe->Format.nBlockAlign;
133 mixwfe->dwChannelMask = speaker_config_to_channel_mask(device->speaker_config);
136 if (!IsEqualGUID(&mixwfe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
137 WAVEFORMATEXTENSIBLE testwfe = *mixwfe;
139 testwfe.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
140 testwfe.Samples.wValidBitsPerSample = testwfe.Format.wBitsPerSample = 32;
141 testwfe.Format.nBlockAlign = testwfe.Format.nChannels * testwfe.Format.wBitsPerSample / 8;
142 testwfe.Format.nAvgBytesPerSec = testwfe.Format.nSamplesPerSec * testwfe.Format.nBlockAlign;
144 if (FAILED(IAudioClient_IsFormatSupported(client, AUDCLNT_SHAREMODE_SHARED, &testwfe.Format, (WAVEFORMATEX**)&retwfe)))
145 w = DSOUND_CopyFormat(&mixwfe->Format);
146 else if (retwfe)
147 w = DSOUND_CopyFormat(&retwfe->Format);
148 else
149 w = DSOUND_CopyFormat(&testwfe.Format);
150 CoTaskMemFree(retwfe);
151 retwfe = NULL;
152 } else
153 w = DSOUND_CopyFormat(&mixwfe->Format);
154 CoTaskMemFree(mixwfe);
155 } else if (device->primary_pwfx->wFormatTag == WAVE_FORMAT_PCM ||
156 device->primary_pwfx->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
157 WAVEFORMATEX *wi = device->primary_pwfx;
158 WAVEFORMATEXTENSIBLE *wfe;
160 /* Convert to WAVEFORMATEXTENSIBLE */
161 w = malloc(sizeof(WAVEFORMATEXTENSIBLE));
162 wfe = (WAVEFORMATEXTENSIBLE*)w;
163 if (!wfe)
164 return DSERR_OUTOFMEMORY;
166 wfe->Format = *wi;
167 w->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
168 w->cbSize = sizeof(*wfe) - sizeof(*w);
169 w->nBlockAlign = w->nChannels * w->wBitsPerSample / 8;
170 w->nAvgBytesPerSec = w->nSamplesPerSec * w->nBlockAlign;
172 wfe->dwChannelMask = 0;
173 if (wi->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
174 w->wBitsPerSample = 32;
175 wfe->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
176 } else
177 wfe->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
178 wfe->Samples.wValidBitsPerSample = w->wBitsPerSample;
179 } else
180 w = DSOUND_CopyFormat(device->primary_pwfx);
182 if (!w)
183 return DSERR_OUTOFMEMORY;
185 hr = IAudioClient_IsFormatSupported(client, AUDCLNT_SHAREMODE_SHARED, w, (WAVEFORMATEX**)&retwfe);
186 if (retwfe) {
187 memcpy(w, retwfe, sizeof(WAVEFORMATEX) + retwfe->Format.cbSize);
188 CoTaskMemFree(retwfe);
190 if (FAILED(hr)) {
191 WARN("IsFormatSupported failed: %08lx\n", hr);
192 free(w);
193 return hr;
195 *wfx = w;
196 return S_OK;
199 static void DSOUND_ReleaseDevice(DirectSoundDevice *device)
201 if(device->client){
202 IAudioClient_Release(device->client);
203 device->client = NULL;
205 if(device->render){
206 IAudioRenderClient_Release(device->render);
207 device->render = NULL;
209 if(device->volume){
210 IAudioStreamVolume_Release(device->volume);
211 device->volume = NULL;
214 if (device->pad) {
215 device->playpos += device->pad;
216 device->playpos %= device->buflen;
217 device->pad = 0;
221 static HRESULT DSOUND_PrimaryOpen(DirectSoundDevice *device, WAVEFORMATEX *wfx, DWORD frames, BOOL forcewave)
223 IDirectSoundBufferImpl** dsb = device->buffers;
224 LPBYTE newbuf;
225 DWORD new_buflen;
226 BOOL mixfloat = FALSE;
227 int i;
229 TRACE("(%p)\n", device);
231 new_buflen = device->buflen;
232 new_buflen -= new_buflen % wfx->nBlockAlign;
234 if (wfx->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
235 (wfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
236 IsEqualGUID(&((WAVEFORMATEXTENSIBLE*)wfx)->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)))
237 mixfloat = TRUE;
239 /* reallocate emulated primary buffer */
240 if (forcewave || !mixfloat) {
241 if (!forcewave)
242 new_buflen = frames * wfx->nChannels * sizeof(float);
244 newbuf = realloc(device->buffer, new_buflen);
246 if (!newbuf) {
247 ERR("failed to allocate primary buffer\n");
248 return DSERR_OUTOFMEMORY;
250 FillMemory(newbuf, new_buflen, (wfx->wBitsPerSample == 8) ? 128 : 0);
251 } else {
252 free(device->buffer);
253 newbuf = NULL;
256 device->buffer = newbuf;
257 device->buflen = new_buflen;
258 free(device->pwfx);
259 device->pwfx = wfx;
261 device->writelead = (wfx->nSamplesPerSec / 100) * wfx->nBlockAlign;
263 TRACE("buflen: %lu, frames %lu\n", device->buflen, frames);
265 if (!mixfloat)
266 device->normfunction = normfunctions[wfx->wBitsPerSample/8 - 1];
267 else
268 device->normfunction = NULL;
270 device->playpos = 0;
272 for (i = 0; i < device->nrofbuffers; i++) {
273 AcquireSRWLockExclusive(&dsb[i]->lock);
274 DSOUND_RecalcFormat(dsb[i]);
275 ReleaseSRWLockExclusive(&dsb[i]->lock);
278 return DS_OK;
281 HRESULT DSOUND_ReopenDevice(DirectSoundDevice *device, BOOL forcewave)
283 HRESULT hres;
284 REFERENCE_TIME period;
285 UINT32 acbuf_frames, aclen_frames;
286 DWORD period_ms;
287 IAudioClient *client = NULL;
288 IAudioRenderClient *render = NULL;
289 IAudioStreamVolume *volume = NULL;
290 DWORD frag_frames;
291 WAVEFORMATEX *wfx = NULL;
292 DWORD oldspeakerconfig = device->speaker_config;
294 TRACE("(%p, %d)\n", device, forcewave);
296 hres = IMMDevice_Activate(device->mmdevice, &IID_IAudioClient,
297 CLSCTX_INPROC_SERVER, NULL, (void **)&client);
298 if(FAILED(hres)){
299 WARN("Activate failed: %08lx\n", hres);
300 return hres;
303 hres = DSOUND_WaveFormat(device, client, forcewave, &wfx);
304 if (FAILED(hres)) {
305 IAudioClient_Release(client);
306 return hres;
309 hres = IAudioClient_Initialize(client,
310 AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_NOPERSIST |
311 AUDCLNT_STREAMFLAGS_EVENTCALLBACK, 800000, 0, wfx, NULL);
312 if(FAILED(hres)){
313 IAudioClient_Release(client);
314 ERR("Initialize failed: %08lx\n", hres);
315 return hres;
318 hres = IAudioClient_SetEventHandle(client, device->sleepev);
319 if (FAILED(hres)) {
320 WARN("SetEventHandle failed: %08lx\n", hres);
321 goto err;
324 hres = IAudioClient_GetService(client, &IID_IAudioRenderClient, (void**)&render);
325 if(FAILED(hres))
326 goto err_service;
328 hres = IAudioClient_GetService(client, &IID_IAudioStreamVolume, (void**)&volume);
329 if(FAILED(hres))
330 goto err_service;
332 /* Now kick off the timer so the event fires periodically */
333 hres = IAudioClient_Start(client);
334 if (FAILED(hres)) {
335 WARN("Start failed with %08lx\n", hres);
336 goto err;
338 hres = IAudioClient_GetStreamLatency(client, &period);
339 if (FAILED(hres)) {
340 WARN("GetStreamLatency failed with %08lx\n", hres);
341 goto err;
343 hres = IAudioClient_GetBufferSize(client, &acbuf_frames);
344 if (FAILED(hres)) {
345 WARN("GetBufferSize failed with %08lx\n", hres);
346 goto err;
349 period_ms = (period + 9999) / 10000;
350 frag_frames = MulDiv(wfx->nSamplesPerSec, period, 10000000);
352 aclen_frames = min(acbuf_frames, 3 * frag_frames);
354 TRACE("period %lu ms frag_frames %lu buf_frames %u\n", period_ms, frag_frames, aclen_frames);
356 hres = DSOUND_PrimaryOpen(device, wfx, aclen_frames, forcewave);
357 if(FAILED(hres))
358 goto err;
360 DSOUND_ReleaseDevice(device);
361 device->client = client;
362 device->render = render;
363 device->volume = volume;
364 device->frag_frames = frag_frames;
365 device->ac_frames = aclen_frames;
367 if (period_ms < 3)
368 device->sleeptime = 5;
369 else
370 device->sleeptime = period_ms * 5 / 2;
372 return S_OK;
374 err_service:
375 WARN("GetService failed: %08lx\n", hres);
376 err:
377 device->speaker_config = oldspeakerconfig;
378 DSOUND_ParseSpeakerConfig(device);
379 if (volume)
380 IAudioStreamVolume_Release(volume);
381 if (render)
382 IAudioRenderClient_Release(render);
383 IAudioClient_Release(client);
384 free(wfx);
385 return hres;
388 HRESULT DSOUND_PrimaryDestroy(DirectSoundDevice *device)
390 TRACE("(%p)\n", device);
392 /* **** */
393 EnterCriticalSection(&(device->mixlock));
395 if(device->primary && (device->primary->ref || device->primary->numIfaces))
396 WARN("Destroying primary buffer while references held (%lu %lu)\n", device->primary->ref, device->primary->numIfaces);
398 free(device->primary);
399 device->primary = NULL;
401 free(device->primary_pwfx);
402 free(device->pwfx);
403 device->pwfx=NULL;
405 LeaveCriticalSection(&(device->mixlock));
406 /* **** */
408 return DS_OK;
411 WAVEFORMATEX *DSOUND_CopyFormat(const WAVEFORMATEX *wfex)
413 WAVEFORMATEX *pwfx;
414 if(wfex->wFormatTag == WAVE_FORMAT_PCM){
415 pwfx = malloc(sizeof(WAVEFORMATEX));
416 if (!pwfx)
417 return NULL;
418 CopyMemory(pwfx, wfex, sizeof(PCMWAVEFORMAT));
419 pwfx->cbSize = 0;
420 }else{
421 pwfx = malloc(sizeof(WAVEFORMATEX) + wfex->cbSize);
422 if (!pwfx)
423 return NULL;
424 CopyMemory(pwfx, wfex, sizeof(WAVEFORMATEX) + wfex->cbSize);
427 if(pwfx->wFormatTag == WAVE_FORMAT_PCM ||
428 (pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
429 IsEqualGUID(&((const WAVEFORMATEXTENSIBLE*)pwfx)->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)))
430 pwfx->nBlockAlign = (pwfx->nChannels * pwfx->wBitsPerSample) / 8;
432 return pwfx;
435 HRESULT primarybuffer_SetFormat(DirectSoundDevice *device, LPCWAVEFORMATEX passed_fmt)
437 HRESULT err = S_OK;
438 WAVEFORMATEX *old_fmt;
439 WAVEFORMATEXTENSIBLE *fmtex, *passed_fmtex = (WAVEFORMATEXTENSIBLE*)passed_fmt;
441 TRACE("(%p,%p)\n", device, passed_fmt);
443 if (device->priolevel == DSSCL_NORMAL) {
444 WARN("failed priority check!\n");
445 return DSERR_PRIOLEVELNEEDED;
448 /* Let's be pedantic! */
449 if (passed_fmt == NULL) {
450 WARN("invalid parameter: passed_fmt==NULL!\n");
451 return DSERR_INVALIDPARAM;
453 TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld,"
454 "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
455 passed_fmt->wFormatTag, passed_fmt->nChannels, passed_fmt->nSamplesPerSec,
456 passed_fmt->nAvgBytesPerSec, passed_fmt->nBlockAlign,
457 passed_fmt->wBitsPerSample, passed_fmt->cbSize);
459 if(passed_fmt->wBitsPerSample < 8 || passed_fmt->wBitsPerSample % 8 != 0 ||
460 passed_fmt->nChannels == 0 || passed_fmt->nSamplesPerSec == 0 ||
461 passed_fmt->nAvgBytesPerSec == 0 ||
462 passed_fmt->nBlockAlign != passed_fmt->nChannels * passed_fmt->wBitsPerSample / 8)
463 return DSERR_INVALIDPARAM;
465 if(passed_fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
466 if(passed_fmtex->Samples.wValidBitsPerSample > passed_fmtex->Format.wBitsPerSample)
467 return DSERR_INVALIDPARAM;
470 /* **** */
471 AcquireSRWLockExclusive(&device->buffer_list_lock);
472 EnterCriticalSection(&(device->mixlock));
474 if (device->priolevel == DSSCL_WRITEPRIMARY) {
475 old_fmt = device->primary_pwfx;
476 device->primary_pwfx = DSOUND_CopyFormat(passed_fmt);
477 fmtex = (WAVEFORMATEXTENSIBLE *)device->primary_pwfx;
478 if (device->primary_pwfx == NULL) {
479 err = DSERR_OUTOFMEMORY;
480 goto out;
483 if (fmtex->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
484 fmtex->Samples.wValidBitsPerSample == 0) {
485 TRACE("Correcting 0 valid bits per sample\n");
486 fmtex->Samples.wValidBitsPerSample = fmtex->Format.wBitsPerSample;
489 err = DSOUND_ReopenDevice(device, TRUE);
490 if (FAILED(err)) {
491 ERR("No formats could be opened\n");
492 free(device->primary_pwfx);
493 device->primary_pwfx = old_fmt;
494 } else
495 free(old_fmt);
496 } else {
497 WAVEFORMATEX *wfx = DSOUND_CopyFormat(passed_fmt);
498 if (wfx) {
499 free(device->primary_pwfx);
500 device->primary_pwfx = wfx;
501 } else
502 err = DSERR_OUTOFMEMORY;
505 out:
506 LeaveCriticalSection(&(device->mixlock));
507 ReleaseSRWLockExclusive(&device->buffer_list_lock);
508 /* **** */
510 return err;
513 /*******************************************************************************
514 * PrimaryBuffer
516 static inline IDirectSoundBufferImpl *impl_from_IDirectSoundBuffer8(IDirectSoundBuffer8 *iface)
518 /* IDirectSoundBuffer and IDirectSoundBuffer8 use the same iface. */
519 return CONTAINING_RECORD(iface, IDirectSoundBufferImpl, IDirectSoundBuffer8_iface);
522 /* This sets this format for the primary buffer only */
523 static HRESULT WINAPI PrimaryBufferImpl_SetFormat(IDirectSoundBuffer8 *iface,
524 const WAVEFORMATEX *wfex)
526 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
527 TRACE("(%p,%p)\n", iface, wfex);
528 return primarybuffer_SetFormat(This->device, wfex);
531 static HRESULT WINAPI PrimaryBufferImpl_SetVolume(IDirectSoundBuffer8 *iface, LONG vol)
533 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
534 DirectSoundDevice *device = This->device;
535 HRESULT hr;
536 float fvol;
537 int i;
539 TRACE("(%p,%ld)\n", iface, vol);
541 if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
542 WARN("control unavailable\n");
543 return DSERR_CONTROLUNAVAIL;
546 if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN)) {
547 WARN("invalid parameter: vol = %ld\n", vol);
548 return DSERR_INVALIDPARAM;
551 /* **** */
552 EnterCriticalSection(&device->mixlock);
554 for (i = 0; i < DS_MAX_CHANNELS; i++) {
555 if (device->pwfx->nChannels > i){
556 hr = IAudioStreamVolume_GetChannelVolume(device->volume, i, &fvol);
557 if (FAILED(hr)){
558 LeaveCriticalSection(&device->mixlock);
559 WARN("GetChannelVolume failed: %08lx\n", hr);
560 return hr;
562 } else
563 fvol=1.0f;
565 device->volpan.dwTotalAmpFactor[i]=((UINT16)(fvol * (DWORD)0xFFFF));
568 DSOUND_AmpFactorToVolPan(&device->volpan);
569 if (vol != device->volpan.lVolume) {
570 device->volpan.lVolume=vol;
571 DSOUND_RecalcVolPan(&device->volpan);
573 for (i = 0; i < DS_MAX_CHANNELS; i++) {
574 if (device->pwfx->nChannels > i){
575 fvol = (float)((device->volpan.dwTotalAmpFactor[i] & 0xFFFF) / (float)0xFFFF);
576 hr = IAudioStreamVolume_SetChannelVolume(device->volume, i, fvol);
577 if (FAILED(hr)){
578 LeaveCriticalSection(&device->mixlock);
579 WARN("SetChannelVolume failed: %08lx\n", hr);
580 return hr;
586 LeaveCriticalSection(&(device->mixlock));
587 /* **** */
589 return DS_OK;
592 static HRESULT WINAPI PrimaryBufferImpl_GetVolume(IDirectSoundBuffer8 *iface, LONG *vol)
594 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
595 DirectSoundDevice *device = This->device;
596 float fvol;
597 HRESULT hr;
598 int i;
600 TRACE("(%p,%p)\n", iface, vol);
602 if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
603 WARN("control unavailable\n");
604 return DSERR_CONTROLUNAVAIL;
607 if (vol == NULL) {
608 WARN("invalid parameter: vol = NULL\n");
609 return DSERR_INVALIDPARAM;
612 EnterCriticalSection(&device->mixlock);
614 for (i = 0; i < DS_MAX_CHANNELS; i++) {
615 if (device->pwfx->nChannels > i){
616 hr = IAudioStreamVolume_GetChannelVolume(device->volume, i, &fvol);
617 if (FAILED(hr)){
618 LeaveCriticalSection(&device->mixlock);
619 WARN("GetChannelVolume failed: %08lx\n", hr);
620 return hr;
622 } else
623 fvol = 1;
625 device->volpan.dwTotalAmpFactor[i] = ((UINT16)(fvol * (DWORD)0xFFFF));
628 DSOUND_AmpFactorToVolPan(&device->volpan);
629 *vol = device->volpan.lVolume;
631 LeaveCriticalSection(&device->mixlock);
633 return DS_OK;
636 static HRESULT WINAPI PrimaryBufferImpl_SetFrequency(IDirectSoundBuffer8 *iface, DWORD freq)
638 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
639 TRACE("(%p,%ld)\n",This,freq);
641 /* You cannot set the frequency of the primary buffer */
642 WARN("control unavailable\n");
643 return DSERR_CONTROLUNAVAIL;
646 static HRESULT WINAPI PrimaryBufferImpl_Play(IDirectSoundBuffer8 *iface, DWORD reserved1,
647 DWORD reserved2, DWORD flags)
649 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
650 DirectSoundDevice *device = This->device;
651 TRACE("(%p,%08lx,%08lx,%08lx)\n", iface, reserved1, reserved2, flags);
653 if (!(flags & DSBPLAY_LOOPING)) {
654 WARN("invalid parameter: flags = %08lx\n", flags);
655 return DSERR_INVALIDPARAM;
658 device->stopped = 0;
660 return DS_OK;
663 static HRESULT WINAPI PrimaryBufferImpl_Stop(IDirectSoundBuffer8 *iface)
665 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
666 DirectSoundDevice *device = This->device;
667 TRACE("(%p)\n", iface);
669 device->stopped = 1;
671 return DS_OK;
674 static ULONG WINAPI PrimaryBufferImpl_AddRef(IDirectSoundBuffer8 *iface)
676 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
677 ULONG ref = InterlockedIncrement(&(This->ref));
678 TRACE("(%p) ref %ld\n", This, ref);
679 if(ref == 1)
680 InterlockedIncrement(&This->numIfaces);
681 return ref;
684 /* Decreases *out by 1 to no less than 0.
685 * Returns the new value of *out. */
686 LONG capped_refcount_dec(LONG *out)
688 LONG ref, oldref;
689 do {
690 ref = *out;
691 if(!ref)
692 return 0;
693 oldref = InterlockedCompareExchange(out, ref - 1, ref);
694 } while(oldref != ref);
695 return ref - 1;
698 static ULONG WINAPI PrimaryBufferImpl_Release(IDirectSoundBuffer8 *iface)
700 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
701 ULONG ref;
703 ref = capped_refcount_dec(&This->ref);
704 if(!ref)
705 capped_refcount_dec(&This->numIfaces);
707 TRACE("(%p) primary ref %ld\n", This, ref);
709 return ref;
712 static HRESULT WINAPI PrimaryBufferImpl_GetCurrentPosition(IDirectSoundBuffer8 *iface,
713 DWORD *playpos, DWORD *writepos)
715 HRESULT hres = DS_OK;
716 UINT32 pad = 0;
717 UINT32 mixpos;
718 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
719 DirectSoundDevice *device = This->device;
720 TRACE("(%p,%p,%p)\n", iface, playpos, writepos);
722 /* **** */
723 EnterCriticalSection(&(device->mixlock));
725 if (device->client)
726 hres = IAudioClient_GetCurrentPadding(device->client, &pad);
727 if (hres != DS_OK) {
728 WARN("IAudioClient_GetCurrentPadding failed\n");
729 LeaveCriticalSection(&(device->mixlock));
730 return hres;
732 mixpos = (device->playpos + pad * device->pwfx->nBlockAlign) % device->buflen;
733 if (playpos)
734 *playpos = mixpos;
735 if (writepos) {
736 *writepos = mixpos;
737 if (!device->stopped) {
738 /* apply the documented 10ms lead to writepos */
739 *writepos += device->writelead;
740 *writepos %= device->buflen;
744 LeaveCriticalSection(&(device->mixlock));
745 /* **** */
747 TRACE("playpos = %ld, writepos = %ld (%p, time=%ld)\n", playpos?*playpos:0, writepos?*writepos:0, device, GetTickCount());
748 return DS_OK;
751 static HRESULT WINAPI PrimaryBufferImpl_GetStatus(IDirectSoundBuffer8 *iface, DWORD *status)
753 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
754 DirectSoundDevice *device = This->device;
755 TRACE("(%p,%p)\n", iface, status);
757 if (status == NULL) {
758 WARN("invalid parameter: status == NULL\n");
759 return DSERR_INVALIDPARAM;
762 *status = 0;
763 if (!device->stopped)
764 *status |= DSBSTATUS_PLAYING | DSBSTATUS_LOOPING;
766 TRACE("status=%lx\n", *status);
767 return DS_OK;
771 static HRESULT WINAPI PrimaryBufferImpl_GetFormat(IDirectSoundBuffer8 *iface, WAVEFORMATEX *lpwf,
772 DWORD wfsize, DWORD *wfwritten)
774 DWORD size;
775 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
776 DirectSoundDevice *device = This->device;
777 TRACE("(%p,%p,%ld,%p)\n", iface, lpwf, wfsize, wfwritten);
779 size = sizeof(WAVEFORMATEX) + device->primary_pwfx->cbSize;
781 if (lpwf) { /* NULL is valid */
782 if (wfsize >= size) {
783 CopyMemory(lpwf,device->primary_pwfx,size);
784 if (wfwritten)
785 *wfwritten = size;
786 } else {
787 WARN("invalid parameter: wfsize too small\n");
788 if (wfwritten)
789 *wfwritten = 0;
790 return DSERR_INVALIDPARAM;
792 } else {
793 if (wfwritten)
794 *wfwritten = sizeof(WAVEFORMATEX) + device->primary_pwfx->cbSize;
795 else {
796 WARN("invalid parameter: wfwritten == NULL\n");
797 return DSERR_INVALIDPARAM;
801 return DS_OK;
804 static HRESULT WINAPI PrimaryBufferImpl_Lock(IDirectSoundBuffer8 *iface, DWORD writecursor,
805 DWORD writebytes, void **lplpaudioptr1, DWORD *audiobytes1, void **lplpaudioptr2,
806 DWORD *audiobytes2, DWORD flags)
808 HRESULT hres;
809 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
810 DirectSoundDevice *device = This->device;
811 TRACE("(%p,%ld,%ld,%p,%p,%p,%p,0x%08lx) at %ld\n",
812 iface,
813 writecursor,
814 writebytes,
815 lplpaudioptr1,
816 audiobytes1,
817 lplpaudioptr2,
818 audiobytes2,
819 flags,
820 GetTickCount()
823 if (!audiobytes1)
824 return DSERR_INVALIDPARAM;
826 if (device->priolevel != DSSCL_WRITEPRIMARY) {
827 WARN("failed priority check!\n");
828 return DSERR_PRIOLEVELNEEDED;
831 /* when this flag is set, writecursor is meaningless and must be calculated */
832 if (flags & DSBLOCK_FROMWRITECURSOR) {
833 /* GetCurrentPosition does too much magic to duplicate here */
834 hres = IDirectSoundBuffer_GetCurrentPosition(iface, NULL, &writecursor);
835 if (hres != DS_OK) {
836 WARN("IDirectSoundBuffer_GetCurrentPosition failed\n");
837 return hres;
841 /* when this flag is set, writebytes is meaningless and must be set */
842 if (flags & DSBLOCK_ENTIREBUFFER)
843 writebytes = device->buflen;
845 if (writecursor >= device->buflen) {
846 WARN("Invalid parameter, writecursor: %lu >= buflen: %lu\n",
847 writecursor, device->buflen);
848 return DSERR_INVALIDPARAM;
851 if (writebytes > device->buflen) {
852 WARN("Invalid parameter, writebytes: %lu > buflen: %lu\n",
853 writebytes, device->buflen);
854 return DSERR_INVALIDPARAM;
857 if (writecursor+writebytes <= device->buflen) {
858 *(LPBYTE*)lplpaudioptr1 = device->buffer+writecursor;
859 *audiobytes1 = writebytes;
860 if (lplpaudioptr2)
861 *(LPBYTE*)lplpaudioptr2 = NULL;
862 if (audiobytes2)
863 *audiobytes2 = 0;
864 TRACE("->%ld.0\n",writebytes);
865 } else {
866 *(LPBYTE*)lplpaudioptr1 = device->buffer+writecursor;
867 *audiobytes1 = device->buflen-writecursor;
868 if (lplpaudioptr2)
869 *(LPBYTE*)lplpaudioptr2 = device->buffer;
870 if (audiobytes2)
871 *audiobytes2 = writebytes-(device->buflen-writecursor);
872 TRACE("->%ld.%ld\n",*audiobytes1,audiobytes2?*audiobytes2:0);
874 return DS_OK;
877 static HRESULT WINAPI PrimaryBufferImpl_SetCurrentPosition(IDirectSoundBuffer8 *iface, DWORD newpos)
879 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
880 TRACE("(%p,%ld)\n",This,newpos);
882 /* You cannot set the position of the primary buffer */
883 WARN("invalid call\n");
884 return DSERR_INVALIDCALL;
887 static HRESULT WINAPI PrimaryBufferImpl_SetPan(IDirectSoundBuffer8 *iface, LONG pan)
889 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
890 DirectSoundDevice *device = This->device;
891 float fvol;
892 HRESULT hr;
893 int i;
895 TRACE("(%p,%ld)\n", iface, pan);
897 if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
898 WARN("control unavailable\n");
899 return DSERR_CONTROLUNAVAIL;
902 if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT)) {
903 WARN("invalid parameter: pan = %ld\n", pan);
904 return DSERR_INVALIDPARAM;
907 /* **** */
908 EnterCriticalSection(&device->mixlock);
910 for (i = 0; i < DS_MAX_CHANNELS; i++) {
911 if (device->pwfx->nChannels > i){
912 hr = IAudioStreamVolume_GetChannelVolume(device->volume, i, &fvol);
913 if (FAILED(hr)){
914 LeaveCriticalSection(&device->mixlock);
915 WARN("GetChannelVolume failed: %08lx\n", hr);
916 return hr;
918 } else
919 fvol = 1;
921 device->volpan.dwTotalAmpFactor[i] = ((UINT16)(fvol * (DWORD)0xFFFF));
924 DSOUND_AmpFactorToVolPan(&device->volpan);
925 if (pan != device->volpan.lPan) {
926 device->volpan.lPan=pan;
927 DSOUND_RecalcVolPan(&device->volpan);
929 for (i = 0; i < DS_MAX_CHANNELS; i++) {
930 if (device->pwfx->nChannels > i) {
931 fvol = (float)((device->volpan.dwTotalAmpFactor[i] & 0xFFFF) / (float)0xFFFF);
932 hr = IAudioStreamVolume_SetChannelVolume(device->volume, i, fvol);
933 if (FAILED(hr)){
934 LeaveCriticalSection(&device->mixlock);
935 WARN("SetChannelVolume failed: %08lx\n", hr);
936 return hr;
942 LeaveCriticalSection(&device->mixlock);
943 /* **** */
945 return DS_OK;
948 static HRESULT WINAPI PrimaryBufferImpl_GetPan(IDirectSoundBuffer8 *iface, LONG *pan)
950 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
951 DirectSoundDevice *device = This->device;
952 float fvol;
953 HRESULT hr;
954 int i;
956 TRACE("(%p,%p)\n", iface, pan);
958 if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
959 WARN("control unavailable\n");
960 return DSERR_CONTROLUNAVAIL;
963 if (pan == NULL) {
964 WARN("invalid parameter: pan == NULL\n");
965 return DSERR_INVALIDPARAM;
968 EnterCriticalSection(&device->mixlock);
970 for (i = 0; i < DS_MAX_CHANNELS; i++) {
971 if (device->pwfx->nChannels > i) {
972 hr = IAudioStreamVolume_GetChannelVolume(device->volume, i, &fvol);
973 if (FAILED(hr)){
974 LeaveCriticalSection(&device->mixlock);
975 WARN("GetChannelVolume failed: %08lx\n", hr);
976 return hr;
978 } else
979 fvol = 1;
981 device->volpan.dwTotalAmpFactor[i] = ((UINT16)(fvol * (DWORD)0xFFFF));
984 DSOUND_AmpFactorToVolPan(&device->volpan);
985 *pan = device->volpan.lPan;
987 LeaveCriticalSection(&device->mixlock);
989 return DS_OK;
992 static HRESULT WINAPI PrimaryBufferImpl_Unlock(IDirectSoundBuffer8 *iface, void *p1, DWORD x1,
993 void *p2, DWORD x2)
995 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
996 DirectSoundDevice *device = This->device;
997 TRACE("(%p,%p,%ld,%p,%ld)\n", iface, p1, x1, p2, x2);
999 if (device->priolevel != DSSCL_WRITEPRIMARY) {
1000 WARN("failed priority check!\n");
1001 return DSERR_PRIOLEVELNEEDED;
1004 if ((p1 && ((BYTE*)p1 < device->buffer || (BYTE*)p1 >= device->buffer + device->buflen)) ||
1005 (p2 && ((BYTE*)p2 < device->buffer || (BYTE*)p2 >= device->buffer + device->buflen)))
1006 return DSERR_INVALIDPARAM;
1008 return DS_OK;
1011 static HRESULT WINAPI PrimaryBufferImpl_Restore(IDirectSoundBuffer8 *iface)
1013 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
1014 FIXME("(%p):stub\n",This);
1015 return DS_OK;
1018 static HRESULT WINAPI PrimaryBufferImpl_GetFrequency(IDirectSoundBuffer8 *iface, DWORD *freq)
1020 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
1021 DirectSoundDevice *device = This->device;
1022 TRACE("(%p,%p)\n", iface, freq);
1024 if (freq == NULL) {
1025 WARN("invalid parameter: freq == NULL\n");
1026 return DSERR_INVALIDPARAM;
1029 if (!(This->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) {
1030 WARN("control unavailable\n");
1031 return DSERR_CONTROLUNAVAIL;
1034 *freq = device->pwfx->nSamplesPerSec;
1035 TRACE("-> %ld\n", *freq);
1037 return DS_OK;
1040 static HRESULT WINAPI PrimaryBufferImpl_Initialize(IDirectSoundBuffer8 *iface, IDirectSound *dsound,
1041 const DSBUFFERDESC *dbsd)
1043 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
1044 WARN("(%p) already initialized\n", This);
1045 return DSERR_ALREADYINITIALIZED;
1048 static HRESULT WINAPI PrimaryBufferImpl_GetCaps(IDirectSoundBuffer8 *iface, DSBCAPS *caps)
1050 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
1051 DirectSoundDevice *device = This->device;
1052 TRACE("(%p,%p)\n", iface, caps);
1054 if (caps == NULL) {
1055 WARN("invalid parameter: caps == NULL\n");
1056 return DSERR_INVALIDPARAM;
1059 if (caps->dwSize < sizeof(*caps)) {
1060 WARN("invalid parameter: caps->dwSize = %ld\n", caps->dwSize);
1061 return DSERR_INVALIDPARAM;
1064 caps->dwFlags = This->dsbd.dwFlags;
1065 caps->dwBufferBytes = device->buflen;
1067 /* Windows reports these as zero */
1068 caps->dwUnlockTransferRate = 0;
1069 caps->dwPlayCpuOverhead = 0;
1071 return DS_OK;
1074 static HRESULT WINAPI PrimaryBufferImpl_QueryInterface(IDirectSoundBuffer8 *iface, REFIID riid,
1075 void **ppobj)
1077 IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer8(iface);
1079 TRACE("(%p,%s,%p)\n", iface, debugstr_guid(riid), ppobj);
1081 if (ppobj == NULL) {
1082 WARN("invalid parameter\n");
1083 return E_INVALIDARG;
1086 *ppobj = NULL; /* assume failure */
1088 if ( IsEqualGUID(riid, &IID_IUnknown) ||
1089 IsEqualGUID(riid, &IID_IDirectSoundBuffer) ) {
1090 IDirectSoundBuffer_AddRef(iface);
1091 *ppobj = iface;
1092 return S_OK;
1095 /* DirectSoundBuffer and DirectSoundBuffer8 are different and */
1096 /* a primary buffer can't have a DirectSoundBuffer8 interface */
1097 if ( IsEqualGUID( &IID_IDirectSoundBuffer8, riid ) ) {
1098 WARN("app requested DirectSoundBuffer8 on primary buffer\n");
1099 return E_NOINTERFACE;
1102 if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
1103 ERR("app requested IDirectSoundNotify on primary buffer\n");
1104 return E_NOINTERFACE;
1107 if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
1108 ERR("app requested IDirectSound3DBuffer on primary buffer\n");
1109 return E_NOINTERFACE;
1112 if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
1113 *ppobj = &This->IDirectSound3DListener_iface;
1114 IDirectSound3DListener_AddRef(&This->IDirectSound3DListener_iface);
1115 return S_OK;
1118 if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
1119 *ppobj = &This->IKsPropertySet_iface;
1120 IKsPropertySet_AddRef(&This->IKsPropertySet_iface);
1121 return S_OK;
1124 FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
1125 return E_NOINTERFACE;
1128 static const IDirectSoundBuffer8Vtbl dspbvt =
1130 PrimaryBufferImpl_QueryInterface,
1131 PrimaryBufferImpl_AddRef,
1132 PrimaryBufferImpl_Release,
1133 PrimaryBufferImpl_GetCaps,
1134 PrimaryBufferImpl_GetCurrentPosition,
1135 PrimaryBufferImpl_GetFormat,
1136 PrimaryBufferImpl_GetVolume,
1137 PrimaryBufferImpl_GetPan,
1138 PrimaryBufferImpl_GetFrequency,
1139 PrimaryBufferImpl_GetStatus,
1140 PrimaryBufferImpl_Initialize,
1141 PrimaryBufferImpl_Lock,
1142 PrimaryBufferImpl_Play,
1143 PrimaryBufferImpl_SetCurrentPosition,
1144 PrimaryBufferImpl_SetFormat,
1145 PrimaryBufferImpl_SetVolume,
1146 PrimaryBufferImpl_SetPan,
1147 PrimaryBufferImpl_SetFrequency,
1148 PrimaryBufferImpl_Stop,
1149 PrimaryBufferImpl_Unlock,
1150 PrimaryBufferImpl_Restore
1153 HRESULT primarybuffer_create(DirectSoundDevice *device, IDirectSoundBufferImpl **ppdsb,
1154 const DSBUFFERDESC *dsbd)
1156 IDirectSoundBufferImpl *dsb;
1157 TRACE("%p,%p,%p)\n",device,ppdsb,dsbd);
1159 if (dsbd->lpwfxFormat) {
1160 WARN("invalid parameter: dsbd->lpwfxFormat != NULL\n");
1161 *ppdsb = NULL;
1162 return DSERR_INVALIDPARAM;
1165 dsb = calloc(1, sizeof(*dsb));
1167 if (dsb == NULL) {
1168 WARN("out of memory\n");
1169 *ppdsb = NULL;
1170 return DSERR_OUTOFMEMORY;
1173 dsb->ref = 0;
1174 dsb->ref3D = 0;
1175 dsb->refiks = 0;
1176 dsb->numIfaces = 0;
1177 dsb->device = device;
1178 dsb->IDirectSoundBuffer8_iface.lpVtbl = &dspbvt;
1179 dsb->IDirectSound3DListener_iface.lpVtbl = &ds3dlvt;
1180 dsb->IKsPropertySet_iface.lpVtbl = &iksbvt;
1181 dsb->dsbd = *dsbd;
1183 /* IDirectSound3DListener */
1184 device->ds3dl.dwSize = sizeof(DS3DLISTENER);
1185 device->ds3dl.vPosition.x = 0.0;
1186 device->ds3dl.vPosition.y = 0.0;
1187 device->ds3dl.vPosition.z = 0.0;
1188 device->ds3dl.vVelocity.x = 0.0;
1189 device->ds3dl.vVelocity.y = 0.0;
1190 device->ds3dl.vVelocity.z = 0.0;
1191 device->ds3dl.vOrientFront.x = 0.0;
1192 device->ds3dl.vOrientFront.y = 0.0;
1193 device->ds3dl.vOrientFront.z = 1.0;
1194 device->ds3dl.vOrientTop.x = 0.0;
1195 device->ds3dl.vOrientTop.y = 1.0;
1196 device->ds3dl.vOrientTop.z = 0.0;
1197 device->ds3dl.flDistanceFactor = DS3D_DEFAULTDISTANCEFACTOR;
1198 device->ds3dl.flRolloffFactor = DS3D_DEFAULTROLLOFFFACTOR;
1199 device->ds3dl.flDopplerFactor = DS3D_DEFAULTDOPPLERFACTOR;
1200 device->ds3dl_need_recalc = TRUE;
1202 TRACE("Created primary buffer at %p\n", dsb);
1203 TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld,"
1204 "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
1205 device->pwfx->wFormatTag, device->pwfx->nChannels,
1206 device->pwfx->nSamplesPerSec, device->pwfx->nAvgBytesPerSec,
1207 device->pwfx->nBlockAlign, device->pwfx->wBitsPerSample,
1208 device->pwfx->cbSize);
1210 IDirectSoundBuffer8_AddRef(&dsb->IDirectSoundBuffer8_iface);
1211 *ppdsb = dsb;
1212 return S_OK;