primary.c 38.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*  			DirectSound
 *
 * Copyright 1998 Marcus Meissner
 * Copyright 1998 Rob Riggs
 * Copyright 2000-2002 TransGaming Technologies, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 23
 *
 * TODO:
 *      When PrimarySetFormat (via ReopenDevice or PrimaryOpen) fails,
 *       it leaves dsound in unusable (not really open) state.
24 25
 */

26
#include <stdarg.h>
27

28
#define COBJMACROS
Robert Reif's avatar
Robert Reif committed
29 30
#define NONAMELESSSTRUCT
#define NONAMELESSUNION
31 32
#include "windef.h"
#include "winbase.h"
33
#include "winuser.h"
34
#include "mmsystem.h"
35
#include "winternl.h"
36 37 38 39 40 41 42
#include "mmddk.h"
#include "wine/debug.h"
#include "dsound.h"
#include "dsound_private.h"

WINE_DEFAULT_DEBUG_CHANNEL(dsound);

43
static DWORD DSOUND_fraglen(DirectSoundDevice *device)
44
{
45 46 47 48 49 50 51 52 53 54 55 56 57 58
    REFERENCE_TIME period;
    HRESULT hr;
    DWORD ret;

    hr = IAudioClient_GetDevicePeriod(device->client, &period, NULL);
    if(FAILED(hr)){
        /* just guess at 10ms */
        WARN("GetDevicePeriod failed: %08x\n", hr);
        ret = MulDiv(device->pwfx->nBlockAlign, device->pwfx->nSamplesPerSec, 100);
    }else
        ret = MulDiv(device->pwfx->nSamplesPerSec * device->pwfx->nBlockAlign, period, 10000000);

    ret -= ret % device->pwfx->nBlockAlign;
    return ret;
59 60
}

61 62
HRESULT DSOUND_ReopenDevice(DirectSoundDevice *device, BOOL forcewave)
{
63 64
    UINT prebuf_frames;
    REFERENCE_TIME prebuf_rt;
65
    HRESULT hres;
66

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    TRACE("(%p, %d)\n", device, forcewave);

    if(device->client){
        IAudioClient_Release(device->client);
        device->client = NULL;
    }
    if(device->render){
        IAudioRenderClient_Release(device->render);
        device->render = NULL;
    }
    if(device->clock){
        IAudioClock_Release(device->clock);
        device->clock = NULL;
    }
    if(device->volume){
        IAudioStreamVolume_Release(device->volume);
        device->volume = NULL;
    }
85

86 87 88 89 90 91 92
    hres = IMMDevice_Activate(device->mmdevice, &IID_IAudioClient,
            CLSCTX_INPROC_SERVER, NULL, (void **)&device->client);
    if(FAILED(hres)){
        WARN("Activate failed: %08x\n", hres);
        return hres;
    }

93
    prebuf_frames = device->prebuf * DSOUND_fraglen(device) / device->pwfx->nBlockAlign;
94 95
    prebuf_rt = (10000000 * (UINT64)prebuf_frames) / device->pwfx->nSamplesPerSec;

96 97
    hres = IAudioClient_Initialize(device->client,
            AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_NOPERSIST,
98
            prebuf_rt, 0, device->pwfx, NULL);
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    if(FAILED(hres)){
        IAudioClient_Release(device->client);
        device->client = NULL;
        WARN("Initialize failed: %08x\n", hres);
        return hres;
    }

    hres = IAudioClient_GetService(device->client, &IID_IAudioRenderClient,
            (void**)&device->render);
    if(FAILED(hres)){
        IAudioClient_Release(device->client);
        device->client = NULL;
        WARN("GetService failed: %08x\n", hres);
        return hres;
    }

    hres = IAudioClient_GetService(device->client, &IID_IAudioClock,
            (void**)&device->clock);
    if(FAILED(hres)){
        IAudioClient_Release(device->client);
        IAudioRenderClient_Release(device->render);
        device->client = NULL;
        device->render = NULL;
        WARN("GetService failed: %08x\n", hres);
        return hres;
    }
125

126 127 128 129 130 131 132 133 134 135
    hres = IAudioClient_GetService(device->client, &IID_IAudioStreamVolume,
            (void**)&device->volume);
    if(FAILED(hres)){
        IAudioClient_Release(device->client);
        IAudioRenderClient_Release(device->render);
        IAudioClock_Release(device->clock);
        device->client = NULL;
        device->render = NULL;
        device->clock = NULL;
        WARN("GetService failed: %08x\n", hres);
136 137
        return hres;
    }
138

139
    return S_OK;
140 141
}

142
static HRESULT DSOUND_PrimaryOpen(DirectSoundDevice *device)
143
{
144
	LPBYTE newbuf;
145

146
	TRACE("(%p)\n", device);
147

148 149
	device->fraglen = DSOUND_fraglen(device);

150 151 152
	/* on original windows, the buffer it set to a fixed size, no matter what the settings are.
	   on windows this size is always fixed (tested on win-xp) */
	if (!device->buflen)
153
		device->buflen = ds_hel_buflen;
154 155 156 157 158 159 160
	device->buflen -= device->buflen % device->pwfx->nBlockAlign;
	while(device->buflen < device->fraglen * device->prebuf){
		device->buflen += ds_hel_buflen;
		device->buflen -= device->buflen % device->pwfx->nBlockAlign;
	}

	device->helfrags = device->buflen / device->fraglen;
161

162 163
	device->mix_buffer_len = ((device->prebuf * device->fraglen) / (device->pwfx->wBitsPerSample / 8)) * sizeof(float);
	device->mix_buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, device->mix_buffer_len);
164 165 166
	if (!device->mix_buffer)
		return DSERR_OUTOFMEMORY;

167 168 169
	if (device->state == STATE_PLAYING) device->state = STATE_STARTING;
	else if (device->state == STATE_STOPPING) device->state = STATE_STOPPED;

170 171
    /* reallocate emulated primary buffer */
    if (device->buffer)
172
        newbuf = HeapReAlloc(GetProcessHeap(),0,device->buffer, device->buflen);
173
    else
174
        newbuf = HeapAlloc(GetProcessHeap(),0, device->buflen);
175

176 177 178 179 180
    if (!newbuf) {
        ERR("failed to allocate primary buffer\n");
        return DSERR_OUTOFMEMORY;
        /* but the old buffer might still exist and must be re-prepared */
    }
181

182
    device->writelead = (device->pwfx->nSamplesPerSec / 100) * device->pwfx->nBlockAlign;
183

184 185
    device->buffer = newbuf;

186 187
    TRACE("buflen: %u, fraglen: %u, helfrags: %u, mix_buffer_len: %u\n",
            device->buflen, device->fraglen, device->helfrags, device->mix_buffer_len);
188

189 190 191
    if(device->pwfx->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
            (device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
             IsEqualGUID(&((WAVEFORMATEXTENSIBLE*)device->pwfx)->SubFormat,
192
                 &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)))
193
        device->normfunction = normfunctions[4];
194
    else
195 196
        device->normfunction = normfunctions[device->pwfx->wBitsPerSample/8 - 1];

197
	FillMemory(device->buffer, device->buflen, (device->pwfx->wBitsPerSample == 8) ? 128 : 0);
198
	FillMemory(device->mix_buffer, device->mix_buffer_len, 0);
199
	device->playing_offs_bytes = device->in_mmdev_bytes = device->playpos = device->mixpos = 0;
200
	return DS_OK;
201 202 203
}


204
static void DSOUND_PrimaryClose(DirectSoundDevice *device)
205
{
206
    HRESULT hr;
207

208
    TRACE("(%p)\n", device);
209

210 211 212 213 214
    if(device->client){
        hr = IAudioClient_Stop(device->client);
        if(FAILED(hr))
            WARN("Stop failed: %08x\n", hr);
    }
215

216
    /* clear the queue */
217
    device->in_mmdev_bytes = 0;
218 219
}

220
HRESULT DSOUND_PrimaryCreate(DirectSoundDevice *device)
221 222
{
	HRESULT err = DS_OK;
223
	TRACE("(%p)\n", device);
224

225
	device->buflen = ds_hel_buflen;
226
	err = DSOUND_PrimaryOpen(device);
227 228 229

	if (err != DS_OK) {
		WARN("DSOUND_PrimaryOpen failed\n");
230
		return err;
231 232
	}

233
	device->state = STATE_STOPPED;
234 235 236
	return DS_OK;
}

237
HRESULT DSOUND_PrimaryDestroy(DirectSoundDevice *device)
238
{
239
	TRACE("(%p)\n", device);
240

241 242
	/* **** */
	EnterCriticalSection(&(device->mixlock));
243

244
	DSOUND_PrimaryClose(device);
245 246 247 248 249 250 251

	if(device->primary && (device->primary->ref || device->primary->numIfaces))
		WARN("Destroying primary buffer while references held (%u %u)\n", device->primary->ref, device->primary->numIfaces);

	HeapFree(GetProcessHeap(), 0, device->primary);
	device->primary = NULL;

252 253
	HeapFree(GetProcessHeap(),0,device->pwfx);
	device->pwfx=NULL;
254 255 256 257

	LeaveCriticalSection(&(device->mixlock));
	/* **** */

258 259 260
	return DS_OK;
}

261
HRESULT DSOUND_PrimaryPlay(DirectSoundDevice *device)
262
{
263
    HRESULT hr;
264

265
    TRACE("(%p)\n", device);
266

267 268 269 270 271 272 273
    hr = IAudioClient_Start(device->client);
    if(FAILED(hr)){
        WARN("Start failed: %08x\n", hr);
        return hr;
    }

    return DS_OK;
274 275
}

276
HRESULT DSOUND_PrimaryStop(DirectSoundDevice *device)
277
{
278
    HRESULT hr;
279

280
    TRACE("(%p)\n", device);
281

282 283 284 285 286
    hr = IAudioClient_Stop(device->client);
    if(FAILED(hr)){
        WARN("Stop failed: %08x\n", hr);
        return hr;
    }
287

288
    return DS_OK;
289 290
}

291
HRESULT DSOUND_PrimaryGetPosition(DirectSoundDevice *device, LPDWORD playpos, LPDWORD writepos)
292
{
293
	TRACE("(%p,%p,%p)\n", device, playpos, writepos);
294

295 296
	/* check if playpos was requested */
	if (playpos)
297
		*playpos = device->playing_offs_bytes;
298 299 300 301

	/* check if writepos was requested */
	if (writepos)
		/* the writepos is the first non-queued position */
302
		*writepos = (device->playing_offs_bytes + device->in_mmdev_bytes) % device->buflen;
303

304
	TRACE("playpos = %d, writepos = %d (%p, time=%d)\n", playpos?*playpos:-1, writepos?*writepos:-1, device, GetTickCount());
305 306 307
	return DS_OK;
}

308 309 310 311 312 313 314 315
static DWORD DSOUND_GetFormatSize(LPCWAVEFORMATEX wfex)
{
	if (wfex->wFormatTag == WAVE_FORMAT_PCM)
		return sizeof(WAVEFORMATEX);
	else
		return sizeof(WAVEFORMATEX) + wfex->cbSize;
}

316 317
LPWAVEFORMATEX DSOUND_CopyFormat(LPCWAVEFORMATEX wfex)
{
318
	DWORD size = DSOUND_GetFormatSize(wfex);
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
	LPWAVEFORMATEX pwfx = HeapAlloc(GetProcessHeap(),0,size);
	if (pwfx == NULL) {
		WARN("out of memory\n");
	} else if (wfex->wFormatTag != WAVE_FORMAT_PCM) {
		CopyMemory(pwfx, wfex, size);
	} else {
		CopyMemory(pwfx, wfex, sizeof(PCMWAVEFORMAT));
		pwfx->cbSize=0;
		if (pwfx->nBlockAlign != pwfx->nChannels * pwfx->wBitsPerSample/8) {
			WARN("Fixing bad nBlockAlign (%u)\n", pwfx->nBlockAlign);
			pwfx->nBlockAlign  = pwfx->nChannels * pwfx->wBitsPerSample/8;
		}
		if (pwfx->nAvgBytesPerSec != pwfx->nSamplesPerSec * pwfx->nBlockAlign) {
			WARN("Fixing bad nAvgBytesPerSec (%u)\n", pwfx->nAvgBytesPerSec);
			pwfx->nAvgBytesPerSec  = pwfx->nSamplesPerSec * pwfx->nBlockAlign;
		}
	}
	return pwfx;
}

339
HRESULT primarybuffer_SetFormat(DirectSoundDevice *device, LPCWAVEFORMATEX passed_fmt)
340
{
341
	HRESULT err = DSERR_BUFFERLOST;
342
	int i;
343
	WAVEFORMATEX *old_fmt;
344
	WAVEFORMATEXTENSIBLE *fmtex, *passed_fmtex = (WAVEFORMATEXTENSIBLE*)passed_fmt;
345
	BOOL forced = (device->priolevel == DSSCL_WRITEPRIMARY);
346

347
	TRACE("(%p,%p)\n", device, passed_fmt);
348

349
	if (device->priolevel == DSSCL_NORMAL) {
350
		WARN("failed priority check!\n");
351 352 353 354
		return DSERR_PRIOLEVELNEEDED;
	}

	/* Let's be pedantic! */
355 356
	if (passed_fmt == NULL) {
		WARN("invalid parameter: passed_fmt==NULL!\n");
357 358
		return DSERR_INVALIDPARAM;
	}
359
	TRACE("(formattag=0x%04x,chans=%d,samplerate=%d,"
360 361 362 363
			  "bytespersec=%d,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
		  passed_fmt->wFormatTag, passed_fmt->nChannels, passed_fmt->nSamplesPerSec,
		  passed_fmt->nAvgBytesPerSec, passed_fmt->nBlockAlign,
		  passed_fmt->wBitsPerSample, passed_fmt->cbSize);
364

365 366 367 368 369 370
	if(passed_fmt->wBitsPerSample < 8 || passed_fmt->wBitsPerSample % 8 != 0 ||
			passed_fmt->nChannels == 0 || passed_fmt->nSamplesPerSec == 0 ||
			passed_fmt->nAvgBytesPerSec == 0 ||
			passed_fmt->nBlockAlign != passed_fmt->nChannels * passed_fmt->wBitsPerSample / 8)
		return DSERR_INVALIDPARAM;

371 372 373 374 375
	if(passed_fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
		if(passed_fmtex->Samples.wValidBitsPerSample > passed_fmtex->Format.wBitsPerSample)
			return DSERR_INVALIDPARAM;
	}

376
	/* **** */
377 378
	RtlAcquireResourceExclusive(&(device->buffer_list_lock), TRUE);
	EnterCriticalSection(&(device->mixlock));
379

380 381 382
	old_fmt = device->pwfx;
	device->pwfx = DSOUND_CopyFormat(passed_fmt);
	fmtex = (WAVEFORMATEXTENSIBLE *)device->pwfx;
383
	if (device->pwfx == NULL) {
384 385
		device->pwfx = old_fmt;
		old_fmt = NULL;
386 387 388
		err = DSERR_OUTOFMEMORY;
		goto done;
	}
389

390 391 392 393 394 395 396
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
		if(fmtex->Samples.wValidBitsPerSample == 0){
			TRACE("Correcting 0 valid bits per sample\n");
			fmtex->Samples.wValidBitsPerSample = fmtex->Format.wBitsPerSample;
		}
	}

397
	DSOUND_PrimaryClose(device);
398

399
	err = DSOUND_ReopenDevice(device, FALSE);
400 401 402 403 404 405 406 407 408 409 410 411 412
	if(SUCCEEDED(err))
		goto opened;

	/* requested format failed, so try others */
	if(device->pwfx->wFormatTag == WAVE_FORMAT_IEEE_FLOAT){
		device->pwfx->wFormatTag = WAVE_FORMAT_PCM;
		device->pwfx->wBitsPerSample = 32;
		device->pwfx->nAvgBytesPerSec = passed_fmt->nSamplesPerSec * device->pwfx->nBlockAlign;
		device->pwfx->nBlockAlign = passed_fmt->nChannels * (device->pwfx->wBitsPerSample / 8);

		err = DSOUND_ReopenDevice(device, FALSE);
		if(SUCCEEDED(err))
			goto opened;
413
	}
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429

	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
			 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)){
		fmtex->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
		device->pwfx->wBitsPerSample = 32;
		device->pwfx->nAvgBytesPerSec = passed_fmt->nSamplesPerSec * device->pwfx->nBlockAlign;
		device->pwfx->nBlockAlign = passed_fmt->nChannels * (device->pwfx->wBitsPerSample / 8);

		err = DSOUND_ReopenDevice(device, FALSE);
		if(SUCCEEDED(err))
			goto opened;
	}

	device->pwfx->wBitsPerSample = 32;
	device->pwfx->nAvgBytesPerSec = passed_fmt->nSamplesPerSec * device->pwfx->nBlockAlign;
	device->pwfx->nBlockAlign = passed_fmt->nChannels * (device->pwfx->wBitsPerSample / 8);
430 431
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
432 433 434 435 436 437 438
	err = DSOUND_ReopenDevice(device, FALSE);
	if(SUCCEEDED(err))
		goto opened;

	device->pwfx->wBitsPerSample = 16;
	device->pwfx->nAvgBytesPerSec = passed_fmt->nSamplesPerSec * device->pwfx->nBlockAlign;
	device->pwfx->nBlockAlign = passed_fmt->nChannels * (device->pwfx->wBitsPerSample / 8);
439 440
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
441 442 443 444 445 446 447
	err = DSOUND_ReopenDevice(device, FALSE);
	if(SUCCEEDED(err))
		goto opened;

	device->pwfx->wBitsPerSample = 8;
	device->pwfx->nAvgBytesPerSec = passed_fmt->nSamplesPerSec * device->pwfx->nBlockAlign;
	device->pwfx->nBlockAlign = passed_fmt->nChannels * (device->pwfx->wBitsPerSample / 8);
448 449
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
450 451 452 453 454 455 456 457
	err = DSOUND_ReopenDevice(device, FALSE);
	if(SUCCEEDED(err))
		goto opened;

	device->pwfx->nChannels = (passed_fmt->nChannels == 2) ? 1 : 2;
	device->pwfx->wBitsPerSample = passed_fmt->wBitsPerSample;
	device->pwfx->nAvgBytesPerSec = passed_fmt->nSamplesPerSec * device->pwfx->nBlockAlign;
	device->pwfx->nBlockAlign = passed_fmt->nChannels * (device->pwfx->wBitsPerSample / 8);
458 459
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
460 461 462 463 464 465 466
	err = DSOUND_ReopenDevice(device, FALSE);
	if(SUCCEEDED(err))
		goto opened;

	device->pwfx->wBitsPerSample = 32;
	device->pwfx->nAvgBytesPerSec = passed_fmt->nSamplesPerSec * device->pwfx->nBlockAlign;
	device->pwfx->nBlockAlign = passed_fmt->nChannels * (device->pwfx->wBitsPerSample / 8);
467 468
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
469 470 471 472 473 474 475
	err = DSOUND_ReopenDevice(device, FALSE);
	if(SUCCEEDED(err))
		goto opened;

	device->pwfx->wBitsPerSample = 16;
	device->pwfx->nAvgBytesPerSec = passed_fmt->nSamplesPerSec * device->pwfx->nBlockAlign;
	device->pwfx->nBlockAlign = passed_fmt->nChannels * (device->pwfx->wBitsPerSample / 8);
476 477
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
478 479 480 481 482 483 484
	err = DSOUND_ReopenDevice(device, FALSE);
	if(SUCCEEDED(err))
		goto opened;

	device->pwfx->wBitsPerSample = 8;
	device->pwfx->nAvgBytesPerSec = passed_fmt->nSamplesPerSec * device->pwfx->nBlockAlign;
	device->pwfx->nBlockAlign = passed_fmt->nChannels * (device->pwfx->wBitsPerSample / 8);
485 486
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
487 488 489 490 491 492 493 494
	err = DSOUND_ReopenDevice(device, FALSE);
	if(SUCCEEDED(err))
		goto opened;

	WARN("No formats could be opened\n");
	goto done;

opened:
495 496 497 498
	err = DSOUND_PrimaryOpen(device);
	if (err != DS_OK) {
		WARN("DSOUND_PrimaryOpen failed\n");
		goto done;
499 500
	}

501
	if (passed_fmt->nSamplesPerSec/100 != device->pwfx->nSamplesPerSec/100 && forced && device->buffer)
502 503
	{
		DSOUND_PrimaryClose(device);
504
		device->pwfx->nSamplesPerSec = passed_fmt->nSamplesPerSec;
505
		err = DSOUND_ReopenDevice(device, TRUE);
506
		if (FAILED(err))
507 508 509
			WARN("DSOUND_ReopenDevice(2) failed: %08x\n", err);
		else if (FAILED((err = DSOUND_PrimaryOpen(device))))
			WARN("DSOUND_PrimaryOpen(2) failed: %08x\n", err);
510 511
	}

512

513 514 515
	if(device->pwfx->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
			(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
			 IsEqualGUID(&((WAVEFORMATEXTENSIBLE*)device->pwfx)->SubFormat,
516
				 &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)))
517
		device->normfunction = normfunctions[4];
518
	else
519
		device->normfunction = normfunctions[device->pwfx->wBitsPerSample/8 - 1];
520

521 522 523
	if (old_fmt->nSamplesPerSec != device->pwfx->nSamplesPerSec ||
			old_fmt->wBitsPerSample != device->pwfx->wBitsPerSample ||
			old_fmt->nChannels != device->pwfx->nChannels) {
524 525
		IDirectSoundBufferImpl** dsb = device->buffers;
		for (i = 0; i < device->nrofbuffers; i++, dsb++) {
526
			/* **** */
527
			RtlAcquireResourceExclusive(&(*dsb)->lock, TRUE);
528

529
			(*dsb)->freqAdjust = (*dsb)->freq / (float)device->pwfx->nSamplesPerSec;
530
			DSOUND_RecalcFormat((*dsb));
531

532
			RtlReleaseResource(&(*dsb)->lock);
533 534 535 536
			/* **** */
		}
	}

537
done:
538 539
	LeaveCriticalSection(&(device->mixlock));
	RtlReleaseResource(&(device->buffer_list_lock));
540 541
	/* **** */

542
	HeapFree(GetProcessHeap(), 0, old_fmt);
543 544 545
	return err;
}

546 547 548
/*******************************************************************************
 *		PrimaryBuffer
 */
549 550 551 552 553 554
static inline IDirectSoundBufferImpl *impl_from_IDirectSoundBuffer(IDirectSoundBuffer *iface)
{
    /* IDirectSoundBuffer and IDirectSoundBuffer8 use the same iface. */
    return CONTAINING_RECORD(iface, IDirectSoundBufferImpl, IDirectSoundBuffer8_iface);
}

555 556 557
/* This sets this format for the primary buffer only */
static HRESULT WINAPI PrimaryBufferImpl_SetFormat(IDirectSoundBuffer *iface,
        const WAVEFORMATEX *wfex)
558
{
559
    IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
560
    TRACE("(%p,%p)\n", iface, wfex);
561
    return primarybuffer_SetFormat(This->device, wfex);
562 563
}

564 565
static HRESULT WINAPI PrimaryBufferImpl_SetVolume(IDirectSoundBuffer *iface, LONG vol)
{
566 567 568 569 570
	IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
	DirectSoundDevice *device = This->device;
	HRESULT hr;
	float lvol, rvol;

571
	TRACE("(%p,%d)\n", iface, vol);
572

573
	if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
574
		WARN("control unavailable\n");
575
		return DSERR_CONTROLUNAVAIL;
576
	}
577

578
	if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN)) {
579
		WARN("invalid parameter: vol = %d\n", vol);
580
		return DSERR_INVALIDPARAM;
581
	}
582 583

	/* **** */
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
	EnterCriticalSection(&device->mixlock);

	hr = IAudioStreamVolume_GetChannelVolume(device->volume, 0, &lvol);
	if(FAILED(hr)){
		LeaveCriticalSection(&device->mixlock);
		WARN("GetChannelVolume failed: %08x\n", hr);
		return hr;
	}

	if(device->pwfx->nChannels > 1){
		hr = IAudioStreamVolume_GetChannelVolume(device->volume, 1, &rvol);
		if(FAILED(hr)){
			LeaveCriticalSection(&device->mixlock);
			WARN("GetChannelVolume failed: %08x\n", hr);
			return hr;
		}
	}else
		rvol = 1;

	device->volpan.dwTotalLeftAmpFactor = ((UINT16)(lvol * (DWORD)0xFFFF));
	device->volpan.dwTotalRightAmpFactor = ((UINT16)(rvol * (DWORD)0xFFFF));
605

606 607
	DSOUND_AmpFactorToVolPan(&device->volpan);
	if (vol != device->volpan.lVolume) {
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
		device->volpan.lVolume=vol;
		DSOUND_RecalcVolPan(&device->volpan);
		lvol = (float)((DWORD)(device->volpan.dwTotalLeftAmpFactor & 0xFFFF) / (float)0xFFFF);
		hr = IAudioStreamVolume_SetChannelVolume(device->volume, 0, lvol);
		if(FAILED(hr)){
			LeaveCriticalSection(&device->mixlock);
			WARN("SetChannelVolume failed: %08x\n", hr);
			return hr;
		}

		if(device->pwfx->nChannels > 1){
			rvol = (float)((DWORD)(device->volpan.dwTotalRightAmpFactor & 0xFFFF) / (float)0xFFFF);
			hr = IAudioStreamVolume_SetChannelVolume(device->volume, 1, rvol);
			if(FAILED(hr)){
				LeaveCriticalSection(&device->mixlock);
				WARN("SetChannelVolume failed: %08x\n", hr);
				return hr;
			}
		}
627
	}
628

629
	LeaveCriticalSection(&(device->mixlock));
630 631
	/* **** */

632
	return DS_OK;
633 634
}

635 636
static HRESULT WINAPI PrimaryBufferImpl_GetVolume(IDirectSoundBuffer *iface, LONG *vol)
{
637 638 639 640
	IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
	DirectSoundDevice *device = This->device;
	float lvol, rvol;
	HRESULT hr;
641
	TRACE("(%p,%p)\n", iface, vol);
642

643
	if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
644 645 646 647
		WARN("control unavailable\n");
		return DSERR_CONTROLUNAVAIL;
	}

648 649
	if (vol == NULL) {
		WARN("invalid parameter: vol = NULL\n");
650
		return DSERR_INVALIDPARAM;
651
	}
652

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
	EnterCriticalSection(&device->mixlock);

	hr = IAudioStreamVolume_GetChannelVolume(device->volume, 0, &lvol);
	if(FAILED(hr)){
		LeaveCriticalSection(&device->mixlock);
		WARN("GetChannelVolume failed: %08x\n", hr);
		return hr;
	}

	if(device->pwfx->nChannels > 1){
		hr = IAudioStreamVolume_GetChannelVolume(device->volume, 1, &rvol);
		if(FAILED(hr)){
			LeaveCriticalSection(&device->mixlock);
			WARN("GetChannelVolume failed: %08x\n", hr);
			return hr;
		}
	}else
		rvol = 1;

	device->volpan.dwTotalLeftAmpFactor = ((UINT16)(lvol * (DWORD)0xFFFF));
	device->volpan.dwTotalRightAmpFactor = ((UINT16)(rvol * (DWORD)0xFFFF));

675 676 677
	DSOUND_AmpFactorToVolPan(&device->volpan);
	*vol = device->volpan.lVolume;

678 679
	LeaveCriticalSection(&device->mixlock);

680 681 682
	return DS_OK;
}

683 684
static HRESULT WINAPI PrimaryBufferImpl_SetFrequency(IDirectSoundBuffer *iface, DWORD freq)
{
685
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
686
	TRACE("(%p,%d)\n",This,freq);
687 688

	/* You cannot set the frequency of the primary buffer */
689
	WARN("control unavailable\n");
690 691 692
	return DSERR_CONTROLUNAVAIL;
}

693 694 695
static HRESULT WINAPI PrimaryBufferImpl_Play(IDirectSoundBuffer *iface, DWORD reserved1,
        DWORD reserved2, DWORD flags)
{
696 697
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
        DirectSoundDevice *device = This->device;
698
	TRACE("(%p,%08x,%08x,%08x)\n", iface, reserved1, reserved2, flags);
699

700
	if (!(flags & DSBPLAY_LOOPING)) {
701
		WARN("invalid parameter: flags = %08x\n", flags);
702
		return DSERR_INVALIDPARAM;
703
	}
704 705

	/* **** */
706
	EnterCriticalSection(&(device->mixlock));
707

708 709 710 711
	if (device->state == STATE_STOPPED)
		device->state = STATE_STARTING;
	else if (device->state == STATE_STOPPING)
		device->state = STATE_PLAYING;
712

713
	LeaveCriticalSection(&(device->mixlock));
714 715 716 717 718
	/* **** */

	return DS_OK;
}

719
static HRESULT WINAPI PrimaryBufferImpl_Stop(IDirectSoundBuffer *iface)
720
{
721 722
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
        DirectSoundDevice *device = This->device;
723
	TRACE("(%p)\n", iface);
724 725

	/* **** */
726
	EnterCriticalSection(&(device->mixlock));
727

728 729 730 731
	if (device->state == STATE_PLAYING)
		device->state = STATE_STOPPING;
	else if (device->state == STATE_STARTING)
		device->state = STATE_STOPPED;
732

733
	LeaveCriticalSection(&(device->mixlock));
734 735 736 737 738
	/* **** */

	return DS_OK;
}

739
static ULONG WINAPI PrimaryBufferImpl_AddRef(IDirectSoundBuffer *iface)
740
{
741
    IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
742
    ULONG ref = InterlockedIncrement(&(This->ref));
743
    TRACE("(%p) ref was %d\n", This, ref - 1);
744 745
    if(ref == 1)
        InterlockedIncrement(&This->numIfaces);
746
    return ref;
747
}
748

749 750 751
/* Decreases *out by 1 to no less than 0.
 * Returns the new value of *out. */
LONG capped_refcount_dec(LONG *out)
752
{
753 754 755 756 757 758 759 760
    LONG ref, oldref;
    do {
        ref = *out;
        if(!ref)
            return 0;
        oldref = InterlockedCompareExchange(out, ref - 1, ref);
    } while(oldref != ref);
    return ref - 1;
761 762
}

763
static ULONG WINAPI PrimaryBufferImpl_Release(IDirectSoundBuffer *iface)
764
{
765
    IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
766 767 768 769 770 771 772
    ULONG ref;

    ref = capped_refcount_dec(&This->ref);
    if(!ref)
        capped_refcount_dec(&This->numIfaces);

    TRACE("(%p) primary ref is now %d\n", This, ref);
773 774

    return ref;
775 776
}

777 778 779
static HRESULT WINAPI PrimaryBufferImpl_GetCurrentPosition(IDirectSoundBuffer *iface,
        DWORD *playpos, DWORD *writepos)
{
780
	HRESULT	hres;
781 782
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
        DirectSoundDevice *device = This->device;
783
	TRACE("(%p,%p,%p)\n", iface, playpos, writepos);
784

785 786 787
	/* **** */
	EnterCriticalSection(&(device->mixlock));

788
	hres = DSOUND_PrimaryGetPosition(device, playpos, writepos);
789 790
	if (hres != DS_OK) {
		WARN("DSOUND_PrimaryGetPosition failed\n");
791
		LeaveCriticalSection(&(device->mixlock));
792 793
		return hres;
	}
794
	if (writepos) {
795
		if (device->state != STATE_STOPPED)
796
			/* apply the documented 10ms lead to writepos */
797 798
			*writepos += device->writelead;
		while (*writepos >= device->buflen) *writepos -= device->buflen;
799
	}
800 801 802 803

	LeaveCriticalSection(&(device->mixlock));
	/* **** */

804
	TRACE("playpos = %d, writepos = %d (%p, time=%d)\n", playpos?*playpos:0, writepos?*writepos:0, device, GetTickCount());
805 806 807
	return DS_OK;
}

808 809
static HRESULT WINAPI PrimaryBufferImpl_GetStatus(IDirectSoundBuffer *iface, DWORD *status)
{
810 811
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
        DirectSoundDevice *device = This->device;
812
	TRACE("(%p,%p)\n", iface, status);
813

814 815
	if (status == NULL) {
		WARN("invalid parameter: status == NULL\n");
816
		return DSERR_INVALIDPARAM;
817
	}
818 819

	*status = 0;
820 821
	if ((device->state == STATE_STARTING) ||
	    (device->state == STATE_PLAYING))
822 823
		*status |= DSBSTATUS_PLAYING | DSBSTATUS_LOOPING;

824
	TRACE("status=%x\n", *status);
825 826 827 828
	return DS_OK;
}


829 830
static HRESULT WINAPI PrimaryBufferImpl_GetFormat(IDirectSoundBuffer *iface, WAVEFORMATEX *lpwf,
        DWORD wfsize, DWORD *wfwritten)
831 832
{
    DWORD size;
833 834
    IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
    DirectSoundDevice *device = This->device;
835
    TRACE("(%p,%p,%d,%p)\n", iface, lpwf, wfsize, wfwritten);
836

837
    size = sizeof(WAVEFORMATEX) + device->pwfx->cbSize;
838 839 840

    if (lpwf) {	/* NULL is valid */
        if (wfsize >= size) {
841
            CopyMemory(lpwf,device->pwfx,size);
842 843 844
            if (wfwritten)
                *wfwritten = size;
        } else {
845
            WARN("invalid parameter: wfsize too small\n");
846 847 848 849 850 851
            if (wfwritten)
                *wfwritten = 0;
            return DSERR_INVALIDPARAM;
        }
    } else {
        if (wfwritten)
852
            *wfwritten = sizeof(WAVEFORMATEX) + device->pwfx->cbSize;
853 854 855 856 857
        else {
            WARN("invalid parameter: wfwritten == NULL\n");
            return DSERR_INVALIDPARAM;
        }
    }
858

859
    return DS_OK;
860 861
}

862 863 864 865
static HRESULT WINAPI PrimaryBufferImpl_Lock(IDirectSoundBuffer *iface, DWORD writecursor,
        DWORD writebytes, void **lplpaudioptr1, DWORD *audiobytes1, void **lplpaudioptr2,
        DWORD *audiobytes2, DWORD flags)
{
866
	HRESULT hres;
867 868
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
        DirectSoundDevice *device = This->device;
869
	TRACE("(%p,%d,%d,%p,%p,%p,%p,0x%08x) at %d\n",
870
		iface,
871 872 873 874 875 876 877 878 879 880
		writecursor,
		writebytes,
		lplpaudioptr1,
		audiobytes1,
		lplpaudioptr2,
		audiobytes2,
		flags,
		GetTickCount()
	);

881 882 883
        if (!audiobytes1)
            return DSERR_INVALIDPARAM;

884
	if (device->priolevel != DSSCL_WRITEPRIMARY) {
885
		WARN("failed priority check!\n");
886
		return DSERR_PRIOLEVELNEEDED;
887
	}
888

889
        /* when this flag is set, writecursor is meaningless and must be calculated */
890 891
	if (flags & DSBLOCK_FROMWRITECURSOR) {
		/* GetCurrentPosition does too much magic to duplicate here */
892
		hres = IDirectSoundBuffer_GetCurrentPosition(iface, NULL, &writecursor);
893 894 895 896
		if (hres != DS_OK) {
			WARN("IDirectSoundBuffer_GetCurrentPosition failed\n");
			return hres;
		}
897
	}
898 899

        /* when this flag is set, writebytes is meaningless and must be set */
900
	if (flags & DSBLOCK_ENTIREBUFFER)
901
		writebytes = device->buflen;
902 903

        if (writecursor >= device->buflen) {
904
                WARN("Invalid parameter, writecursor: %u >= buflen: %u\n",
905 906 907
		     writecursor, device->buflen);
                return DSERR_INVALIDPARAM;
        }
908

909
        if (writebytes > device->buflen) {
910
                WARN("Invalid parameter, writebytes: %u > buflen: %u\n",
911 912 913
		     writebytes, device->buflen);
                return DSERR_INVALIDPARAM;
        }
914

915 916 917 918 919 920 921 922
	if (writecursor+writebytes <= device->buflen) {
		*(LPBYTE*)lplpaudioptr1 = device->buffer+writecursor;
		*audiobytes1 = writebytes;
		if (lplpaudioptr2)
			*(LPBYTE*)lplpaudioptr2 = NULL;
		if (audiobytes2)
			*audiobytes2 = 0;
		TRACE("->%d.0\n",writebytes);
923
	} else {
924 925 926 927 928 929 930
		*(LPBYTE*)lplpaudioptr1 = device->buffer+writecursor;
		*audiobytes1 = device->buflen-writecursor;
		if (lplpaudioptr2)
			*(LPBYTE*)lplpaudioptr2 = device->buffer;
		if (audiobytes2)
			*audiobytes2 = writebytes-(device->buflen-writecursor);
		TRACE("->%d.%d\n",*audiobytes1,audiobytes2?*audiobytes2:0);
931 932 933 934
	}
	return DS_OK;
}

935 936
static HRESULT WINAPI PrimaryBufferImpl_SetCurrentPosition(IDirectSoundBuffer *iface, DWORD newpos)
{
937
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
938
	TRACE("(%p,%d)\n",This,newpos);
939 940

	/* You cannot set the position of the primary buffer */
941
	WARN("invalid call\n");
942 943 944
	return DSERR_INVALIDCALL;
}

945 946
static HRESULT WINAPI PrimaryBufferImpl_SetPan(IDirectSoundBuffer *iface, LONG pan)
{
947 948 949 950
	IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
	DirectSoundDevice *device = This->device;
	float lvol, rvol;
	HRESULT hr;
951
	TRACE("(%p,%d)\n", iface, pan);
952

953
	if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
954 955 956 957 958
		WARN("control unavailable\n");
		return DSERR_CONTROLUNAVAIL;
	}

	if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT)) {
959
		WARN("invalid parameter: pan = %d\n", pan);
960 961 962 963
		return DSERR_INVALIDPARAM;
	}

	/* **** */
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
	EnterCriticalSection(&device->mixlock);

	hr = IAudioStreamVolume_GetChannelVolume(device->volume, 0, &lvol);
	if(FAILED(hr)){
		LeaveCriticalSection(&device->mixlock);
		WARN("GetChannelVolume failed: %08x\n", hr);
		return hr;
	}

	if(device->pwfx->nChannels > 1){
		hr = IAudioStreamVolume_GetChannelVolume(device->volume, 1, &rvol);
		if(FAILED(hr)){
			LeaveCriticalSection(&device->mixlock);
			WARN("GetChannelVolume failed: %08x\n", hr);
			return hr;
		}
	}else
		rvol = 1;

	device->volpan.dwTotalLeftAmpFactor = ((UINT16)(lvol * (DWORD)0xFFFF));
	device->volpan.dwTotalRightAmpFactor = ((UINT16)(rvol * (DWORD)0xFFFF));
985

986 987 988 989
	DSOUND_AmpFactorToVolPan(&device->volpan);
	if (pan != device->volpan.lPan) {
		device->volpan.lPan=pan;
		DSOUND_RecalcVolPan(&device->volpan);
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007

		lvol = (float)((DWORD)(device->volpan.dwTotalLeftAmpFactor & 0xFFFF) / (float)0xFFFF);
		hr = IAudioStreamVolume_SetChannelVolume(device->volume, 0, lvol);
		if(FAILED(hr)){
			LeaveCriticalSection(&device->mixlock);
			WARN("SetChannelVolume failed: %08x\n", hr);
			return hr;
		}

		if(device->pwfx->nChannels > 1){
			rvol = (float)((DWORD)(device->volpan.dwTotalRightAmpFactor & 0xFFFF) / (float)0xFFFF);
			hr = IAudioStreamVolume_SetChannelVolume(device->volume, 1, rvol);
			if(FAILED(hr)){
				LeaveCriticalSection(&device->mixlock);
				WARN("SetChannelVolume failed: %08x\n", hr);
				return hr;
			}
		}
1008
	}
1009

1010
	LeaveCriticalSection(&device->mixlock);
1011 1012
	/* **** */

1013
	return DS_OK;
1014 1015
}

1016 1017
static HRESULT WINAPI PrimaryBufferImpl_GetPan(IDirectSoundBuffer *iface, LONG *pan)
{
1018 1019 1020 1021
	IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
	DirectSoundDevice *device = This->device;
	float lvol, rvol;
	HRESULT hr;
1022
	TRACE("(%p,%p)\n", iface, pan);
1023

1024
	if (!(This->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
1025 1026 1027 1028
		WARN("control unavailable\n");
		return DSERR_CONTROLUNAVAIL;
	}

1029 1030
	if (pan == NULL) {
		WARN("invalid parameter: pan == NULL\n");
1031
		return DSERR_INVALIDPARAM;
1032
	}
1033

1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
	EnterCriticalSection(&device->mixlock);

	hr = IAudioStreamVolume_GetChannelVolume(device->volume, 0, &lvol);
	if(FAILED(hr)){
		LeaveCriticalSection(&device->mixlock);
		WARN("GetChannelVolume failed: %08x\n", hr);
		return hr;
	}

	if(device->pwfx->nChannels > 1){
		hr = IAudioStreamVolume_GetChannelVolume(device->volume, 1, &rvol);
		if(FAILED(hr)){
			LeaveCriticalSection(&device->mixlock);
			WARN("GetChannelVolume failed: %08x\n", hr);
			return hr;
		}
	}else
		rvol = 1;

	device->volpan.dwTotalLeftAmpFactor = ((UINT16)(lvol * (DWORD)0xFFFF));
	device->volpan.dwTotalRightAmpFactor = ((UINT16)(rvol * (DWORD)0xFFFF));

1056
	DSOUND_AmpFactorToVolPan(&device->volpan);
1057
	*pan = device->volpan.lPan;
1058 1059 1060

	LeaveCriticalSection(&device->mixlock);

1061 1062 1063
	return DS_OK;
}

1064 1065 1066
static HRESULT WINAPI PrimaryBufferImpl_Unlock(IDirectSoundBuffer *iface, void *p1, DWORD x1,
        void *p2, DWORD x2)
{
1067 1068
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
        DirectSoundDevice *device = This->device;
1069
	TRACE("(%p,%p,%d,%p,%d)\n", iface, p1, x1, p2, x2);
1070

1071
	if (device->priolevel != DSSCL_WRITEPRIMARY) {
1072
		WARN("failed priority check!\n");
1073
		return DSERR_PRIOLEVELNEEDED;
1074
	}
1075

1076 1077 1078 1079 1080 1081
    if((p1 && ((BYTE*)p1 < device->buffer ||
                    (BYTE*)p1 >= device->buffer + device->buflen)) ||
            (p2 && ((BYTE*)p2 < device->buffer ||
                    (BYTE*)p2 >= device->buffer + device->buflen)))
        return DSERR_INVALIDPARAM;

1082 1083 1084
	return DS_OK;
}

1085 1086
static HRESULT WINAPI PrimaryBufferImpl_Restore(IDirectSoundBuffer *iface)
{
1087
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
1088 1089 1090 1091
	FIXME("(%p):stub\n",This);
	return DS_OK;
}

1092 1093
static HRESULT WINAPI PrimaryBufferImpl_GetFrequency(IDirectSoundBuffer *iface, DWORD *freq)
{
1094 1095
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
        DirectSoundDevice *device = This->device;
1096
	TRACE("(%p,%p)\n", iface, freq);
1097

1098 1099
	if (freq == NULL) {
		WARN("invalid parameter: freq == NULL\n");
1100
		return DSERR_INVALIDPARAM;
1101
	}
1102

1103
	if (!(This->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) {
1104 1105 1106 1107
		WARN("control unavailable\n");
		return DSERR_CONTROLUNAVAIL;
	}

1108
	*freq = device->pwfx->nSamplesPerSec;
1109
	TRACE("-> %d\n", *freq);
1110 1111 1112 1113

	return DS_OK;
}

1114 1115 1116
static HRESULT WINAPI PrimaryBufferImpl_Initialize(IDirectSoundBuffer *iface, IDirectSound *dsound,
        const DSBUFFERDESC *dbsd)
{
1117
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
1118
	WARN("(%p) already initialized\n", This);
1119 1120 1121
	return DSERR_ALREADYINITIALIZED;
}

1122 1123
static HRESULT WINAPI PrimaryBufferImpl_GetCaps(IDirectSoundBuffer *iface, DSBCAPS *caps)
{
1124 1125
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
        DirectSoundDevice *device = This->device;
1126
  	TRACE("(%p,%p)\n", iface, caps);
1127

1128 1129
	if (caps == NULL) {
		WARN("invalid parameter: caps == NULL\n");
1130
		return DSERR_INVALIDPARAM;
1131 1132 1133
	}

	if (caps->dwSize < sizeof(*caps)) {
1134
		WARN("invalid parameter: caps->dwSize = %d\n", caps->dwSize);
1135 1136
		return DSERR_INVALIDPARAM;
	}
1137

1138
	caps->dwFlags = This->dsbd.dwFlags;
1139
	caps->dwBufferBytes = device->buflen;
1140

1141 1142
	/* Windows reports these as zero */
	caps->dwUnlockTransferRate = 0;
1143 1144 1145 1146 1147
	caps->dwPlayCpuOverhead = 0;

	return DS_OK;
}

1148 1149 1150
static HRESULT WINAPI PrimaryBufferImpl_QueryInterface(IDirectSoundBuffer *iface, REFIID riid,
        void **ppobj)
{
1151
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
1152

1153
	TRACE("(%p,%s,%p)\n", iface, debugstr_guid(riid), ppobj);
1154

1155 1156 1157 1158 1159
	if (ppobj == NULL) {
		WARN("invalid parameter\n");
		return E_INVALIDARG;
	}

1160 1161
	*ppobj = NULL;	/* assume failure */

1162
	if ( IsEqualGUID(riid, &IID_IUnknown) ||
1163
	     IsEqualGUID(riid, &IID_IDirectSoundBuffer) ) {
1164 1165
		IDirectSoundBuffer_AddRef(iface);
		*ppobj = iface;
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
		return S_OK;
	}

	/* DirectSoundBuffer and DirectSoundBuffer8 are different and */
	/* a primary buffer can't have a DirectSoundBuffer8 interface */
	if ( IsEqualGUID( &IID_IDirectSoundBuffer8, riid ) ) {
		WARN("app requested DirectSoundBuffer8 on primary buffer\n");
		return E_NOINTERFACE;
	}

1176 1177
	if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
		ERR("app requested IDirectSoundNotify on primary buffer\n");
1178
		/* FIXME: should we support this? */
1179
		return E_NOINTERFACE;
1180 1181 1182 1183 1184 1185 1186 1187
	}

	if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
		ERR("app requested IDirectSound3DBuffer on primary buffer\n");
		return E_NOINTERFACE;
	}

        if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
1188 1189 1190
                *ppobj = &This->IDirectSound3DListener_iface;
                IDirectSound3DListener_AddRef(&This->IDirectSound3DListener_iface);
                return S_OK;
1191 1192 1193
	}

	if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
1194 1195 1196
                *ppobj = &This->IKsPropertySet_iface;
                IKsPropertySet_AddRef(&This->IKsPropertySet_iface);
                return S_OK;
1197 1198 1199 1200 1201 1202
	}

	FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
	return E_NOINTERFACE;
}

1203
static const IDirectSoundBufferVtbl dspbvt =
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
{
	PrimaryBufferImpl_QueryInterface,
	PrimaryBufferImpl_AddRef,
	PrimaryBufferImpl_Release,
	PrimaryBufferImpl_GetCaps,
	PrimaryBufferImpl_GetCurrentPosition,
	PrimaryBufferImpl_GetFormat,
	PrimaryBufferImpl_GetVolume,
	PrimaryBufferImpl_GetPan,
        PrimaryBufferImpl_GetFrequency,
	PrimaryBufferImpl_GetStatus,
	PrimaryBufferImpl_Initialize,
	PrimaryBufferImpl_Lock,
	PrimaryBufferImpl_Play,
	PrimaryBufferImpl_SetCurrentPosition,
	PrimaryBufferImpl_SetFormat,
	PrimaryBufferImpl_SetVolume,
	PrimaryBufferImpl_SetPan,
	PrimaryBufferImpl_SetFrequency,
	PrimaryBufferImpl_Stop,
	PrimaryBufferImpl_Unlock,
1225
	PrimaryBufferImpl_Restore
1226 1227
};

1228 1229
HRESULT primarybuffer_create(DirectSoundDevice *device, IDirectSoundBufferImpl **ppdsb,
	const DSBUFFERDESC *dsbd)
1230
{
1231
	IDirectSoundBufferImpl *dsb;
Robert Reif's avatar
Robert Reif committed
1232
	TRACE("%p,%p,%p)\n",device,ppdsb,dsbd);
1233

1234 1235
	if (dsbd->lpwfxFormat) {
		WARN("invalid parameter: dsbd->lpwfxFormat != NULL\n");
Robert Reif's avatar
Robert Reif committed
1236
		*ppdsb = NULL;
1237
		return DSERR_INVALIDPARAM;
1238
	}
1239

1240
	dsb = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*dsb));
1241 1242 1243

	if (dsb == NULL) {
		WARN("out of memory\n");
Robert Reif's avatar
Robert Reif committed
1244
		*ppdsb = NULL;
1245 1246 1247
		return DSERR_OUTOFMEMORY;
	}

1248
        dsb->ref = 0;
1249
        dsb->ref3D = 0;
1250
        dsb->refiks = 0;
1251
        dsb->numIfaces = 0;
Robert Reif's avatar
Robert Reif committed
1252
	dsb->device = device;
1253
	dsb->IDirectSoundBuffer8_iface.lpVtbl = (IDirectSoundBuffer8Vtbl *)&dspbvt;
1254
        dsb->IDirectSound3DListener_iface.lpVtbl = &ds3dlvt;
1255
        dsb->IKsPropertySet_iface.lpVtbl = &iksbvt;
1256
	dsb->dsbd = *dsbd;
1257

1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
        /* IDirectSound3DListener */
        device->ds3dl.dwSize = sizeof(DS3DLISTENER);
        device->ds3dl.vPosition.x = 0.0;
        device->ds3dl.vPosition.y = 0.0;
        device->ds3dl.vPosition.z = 0.0;
        device->ds3dl.vVelocity.x = 0.0;
        device->ds3dl.vVelocity.y = 0.0;
        device->ds3dl.vVelocity.z = 0.0;
        device->ds3dl.vOrientFront.x = 0.0;
        device->ds3dl.vOrientFront.y = 0.0;
        device->ds3dl.vOrientFront.z = 1.0;
        device->ds3dl.vOrientTop.x = 0.0;
        device->ds3dl.vOrientTop.y = 1.0;
        device->ds3dl.vOrientTop.z = 0.0;
        device->ds3dl.flDistanceFactor = DS3D_DEFAULTDISTANCEFACTOR;
        device->ds3dl.flRolloffFactor = DS3D_DEFAULTROLLOFFFACTOR;
        device->ds3dl.flDopplerFactor = DS3D_DEFAULTDOPPLERFACTOR;
        device->ds3dl_need_recalc = TRUE;

1277
	TRACE("Created primary buffer at %p\n", dsb);
1278 1279
	TRACE("(formattag=0x%04x,chans=%d,samplerate=%d,"
		"bytespersec=%d,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
Robert Reif's avatar
Robert Reif committed
1280 1281 1282 1283
		device->pwfx->wFormatTag, device->pwfx->nChannels,
                device->pwfx->nSamplesPerSec, device->pwfx->nAvgBytesPerSec,
                device->pwfx->nBlockAlign, device->pwfx->wBitsPerSample,
                device->pwfx->cbSize);
1284

1285
        IDirectSoundBuffer_AddRef(&dsb->IDirectSoundBuffer8_iface);
Robert Reif's avatar
Robert Reif committed
1286
	*ppdsb = dsb;
1287 1288
	return S_OK;
}