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 44 45 46 47 48 49 50 51
/** Calculate how long a fragment length of about 10 ms should be in frames
 *
 * nSamplesPerSec: Frequency rate in samples per second
 * nBlockAlign: Size of a single blockalign
 *
 * Returns:
 * Size in bytes of a single fragment
 */
DWORD DSOUND_fraglen(DWORD nSamplesPerSec, DWORD nBlockAlign)
52
{
53 54 55 56 57 58 59
    /* Given a timer delay of 10ms, the fragment size is approximately:
     *     fraglen = (nSamplesPerSec * 10 / 1000) * nBlockAlign
     * ==> fraglen = (nSamplesPerSec / 100) * nBlockSize
     *
     * ALSA uses buffers that are powers of 2. Because of this, fraglen
     * is rounded up to the nearest power of 2:
     */
60

61 62
    if (nSamplesPerSec <= 12800)
        return 128 * nBlockAlign;
63

64 65
    if (nSamplesPerSec <= 25600)
        return 256 * nBlockAlign;
66

67 68
    if (nSamplesPerSec <= 51200)
        return 512 * nBlockAlign;
69

70
    return 1024 * nBlockAlign;
71 72 73 74 75
}

static void DSOUND_RecalcPrimary(DirectSoundDevice *device)
{
    TRACE("(%p)\n", device);
76

77 78 79
    device->fraglen = DSOUND_fraglen(device->pwfx->nSamplesPerSec, device->pwfx->nBlockAlign);
    device->helfrags = device->buflen / device->fraglen;
    TRACE("fraglen=%d helfrags=%d\n", device->fraglen, device->helfrags);
80

81 82
    /* calculate the 10ms write lead */
    device->writelead = (device->pwfx->nSamplesPerSec / 100) * device->pwfx->nBlockAlign;
83 84
}

85 86
HRESULT DSOUND_ReopenDevice(DirectSoundDevice *device, BOOL forcewave)
{
87 88
    UINT prebuf_frames;
    REFERENCE_TIME prebuf_rt;
89
    HRESULT hres;
90

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    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;
    }
109

110 111 112 113 114 115 116
    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;
    }

117
    prebuf_frames = device->prebuf * DSOUND_fraglen(device->pwfx->nSamplesPerSec, device->pwfx->nBlockAlign) / device->pwfx->nBlockAlign;
118 119
    prebuf_rt = (10000000 * (UINT64)prebuf_frames) / device->pwfx->nSamplesPerSec;

120 121
    hres = IAudioClient_Initialize(device->client,
            AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_NOPERSIST,
122
            prebuf_rt, 0, device->pwfx, NULL);
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    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;
    }
149

150 151 152 153 154 155 156 157 158 159
    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);
160 161
        return hres;
    }
162

163
    return S_OK;
164 165
}

166
static HRESULT DSOUND_PrimaryOpen(DirectSoundDevice *device)
167
{
168
	DWORD buflen;
169
	LPBYTE newbuf;
170

171
	TRACE("(%p)\n", device);
172

173 174 175
	/* 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)
176 177
		device->buflen = ds_hel_buflen;
	buflen = device->buflen;
178 179 180
	buflen -= buflen % device->pwfx->nBlockAlign;
	device->buflen = buflen;

181 182 183 184 185
	device->mix_buffer_len = DSOUND_bufpos_to_mixpos(device, device->buflen);
	device->mix_buffer = HeapAlloc(GetProcessHeap(), 0, device->mix_buffer_len);
	if (!device->mix_buffer)
		return DSERR_OUTOFMEMORY;

186 187 188
	if (device->state == STATE_PLAYING) device->state = STATE_STARTING;
	else if (device->state == STATE_STOPPING) device->state = STATE_STOPPED;

189
    TRACE("desired buflen=%d, old buffer=%p\n", buflen, device->buffer);
190

191 192 193 194 195
    /* reallocate emulated primary buffer */
    if (device->buffer)
        newbuf = HeapReAlloc(GetProcessHeap(),0,device->buffer, buflen);
    else
        newbuf = HeapAlloc(GetProcessHeap(),0, buflen);
196

197 198 199 200 201
    if (!newbuf) {
        ERR("failed to allocate primary buffer\n");
        return DSERR_OUTOFMEMORY;
        /* but the old buffer might still exist and must be re-prepared */
    }
202

203
    DSOUND_RecalcPrimary(device);
204

205 206
    device->buffer = newbuf;

207
    TRACE("fraglen=%d\n", device->fraglen);
208

209 210
	device->mixfunction = mixfunctions[device->pwfx->wBitsPerSample/8 - 1];
	device->normfunction = normfunctions[device->pwfx->wBitsPerSample/8 - 1];
211
	FillMemory(device->buffer, device->buflen, (device->pwfx->wBitsPerSample == 8) ? 128 : 0);
212
	FillMemory(device->mix_buffer, device->mix_buffer_len, 0);
213 214
	device->last_pos_bytes = device->pwplay = device->pwqueue = device->playpos = device->mixpos = 0;
	return DS_OK;
215 216 217
}


218
static void DSOUND_PrimaryClose(DirectSoundDevice *device)
219
{
220
    HRESULT hr;
221

222
    TRACE("(%p)\n", device);
223

224
    device->pwqueue = (DWORD)-1; /* resetting queues */
225 226 227 228 229 230

    if(device->client){
        hr = IAudioClient_Stop(device->client);
        if(FAILED(hr))
            WARN("Stop failed: %08x\n", hr);
    }
231

232 233
    /* clear the queue */
    device->pwqueue = 0;
234 235
}

236
HRESULT DSOUND_PrimaryCreate(DirectSoundDevice *device)
237 238
{
	HRESULT err = DS_OK;
239
	TRACE("(%p)\n", device);
240

241
	device->buflen = ds_hel_buflen;
242
	err = DSOUND_PrimaryOpen(device);
243 244 245

	if (err != DS_OK) {
		WARN("DSOUND_PrimaryOpen failed\n");
246
		return err;
247 248
	}

249
	device->state = STATE_STOPPED;
250 251 252
	return DS_OK;
}

253
HRESULT DSOUND_PrimaryDestroy(DirectSoundDevice *device)
254
{
255
	TRACE("(%p)\n", device);
256

257 258
	/* **** */
	EnterCriticalSection(&(device->mixlock));
259

260
	DSOUND_PrimaryClose(device);
261 262
	HeapFree(GetProcessHeap(),0,device->pwfx);
	device->pwfx=NULL;
263 264 265 266

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

267 268 269
	return DS_OK;
}

270
HRESULT DSOUND_PrimaryPlay(DirectSoundDevice *device)
271
{
272
    HRESULT hr;
273

274
    TRACE("(%p)\n", device);
275

276 277 278 279 280 281 282
    hr = IAudioClient_Start(device->client);
    if(FAILED(hr)){
        WARN("Start failed: %08x\n", hr);
        return hr;
    }

    return DS_OK;
283 284
}

285
HRESULT DSOUND_PrimaryStop(DirectSoundDevice *device)
286
{
287
    HRESULT hr;
288

289
    TRACE("(%p)\n", device);
290

291 292 293 294 295
    hr = IAudioClient_Stop(device->client);
    if(FAILED(hr)){
        WARN("Stop failed: %08x\n", hr);
        return hr;
    }
296

297
    return DS_OK;
298 299
}

300
HRESULT DSOUND_PrimaryGetPosition(DirectSoundDevice *device, LPDWORD playpos, LPDWORD writepos)
301
{
302
	TRACE("(%p,%p,%p)\n", device, playpos, writepos);
303

304
	TRACE("pwplay=%i, pwqueue=%i\n", device->pwplay, device->pwqueue);
305

306 307 308 309 310 311 312 313 314
	/* check if playpos was requested */
	if (playpos)
		/* use the cached play position */
		*playpos = device->pwplay * device->fraglen;

	/* check if writepos was requested */
	if (writepos)
		/* the writepos is the first non-queued position */
		*writepos = ((device->pwplay + device->pwqueue) % device->helfrags) * device->fraglen;
315

316
	TRACE("playpos = %d, writepos = %d (%p, time=%d)\n", playpos?*playpos:-1, writepos?*writepos:-1, device, GetTickCount());
317 318 319
	return DS_OK;
}

320 321 322 323 324 325 326 327
static DWORD DSOUND_GetFormatSize(LPCWAVEFORMATEX wfex)
{
	if (wfex->wFormatTag == WAVE_FORMAT_PCM)
		return sizeof(WAVEFORMATEX);
	else
		return sizeof(WAVEFORMATEX) + wfex->cbSize;
}

328 329
LPWAVEFORMATEX DSOUND_CopyFormat(LPCWAVEFORMATEX wfex)
{
330
	DWORD size = DSOUND_GetFormatSize(wfex);
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
	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;
}

351
HRESULT primarybuffer_SetFormat(DirectSoundDevice *device, LPCWAVEFORMATEX passed_fmt)
352
{
353
	HRESULT err = DSERR_BUFFERLOST;
354
	int i;
355
	WAVEFORMATEX *old_fmt;
356
	WAVEFORMATEXTENSIBLE *fmtex, *passed_fmtex = (WAVEFORMATEXTENSIBLE*)passed_fmt;
357
	BOOL forced = (device->priolevel == DSSCL_WRITEPRIMARY);
358

359
	TRACE("(%p,%p)\n", device, passed_fmt);
360

361
	if (device->priolevel == DSSCL_NORMAL) {
362
		WARN("failed priority check!\n");
363 364 365 366
		return DSERR_PRIOLEVELNEEDED;
	}

	/* Let's be pedantic! */
367 368
	if (passed_fmt == NULL) {
		WARN("invalid parameter: passed_fmt==NULL!\n");
369 370
		return DSERR_INVALIDPARAM;
	}
371
	TRACE("(formattag=0x%04x,chans=%d,samplerate=%d,"
372 373 374 375
			  "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);
376

377 378 379 380 381 382
	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;

383 384 385 386 387
	if(passed_fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
		if(passed_fmtex->Samples.wValidBitsPerSample > passed_fmtex->Format.wBitsPerSample)
			return DSERR_INVALIDPARAM;
	}

388
	/* **** */
389 390
	RtlAcquireResourceExclusive(&(device->buffer_list_lock), TRUE);
	EnterCriticalSection(&(device->mixlock));
391

392 393 394
	old_fmt = device->pwfx;
	device->pwfx = DSOUND_CopyFormat(passed_fmt);
	fmtex = (WAVEFORMATEXTENSIBLE *)device->pwfx;
395
	if (device->pwfx == NULL) {
396 397
		device->pwfx = old_fmt;
		old_fmt = NULL;
398 399 400
		err = DSERR_OUTOFMEMORY;
		goto done;
	}
401

402 403 404 405 406 407 408
	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;
		}
	}

409
	DSOUND_PrimaryClose(device);
410

411
	err = DSOUND_ReopenDevice(device, FALSE);
412 413 414 415 416 417 418 419 420 421 422 423 424
	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;
425
	}
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

	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);
442 443
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
444 445 446 447 448 449 450
	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);
451 452
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
453 454 455 456 457 458 459
	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);
460 461
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
462 463 464 465 466 467 468 469
	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);
470 471
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
472 473 474 475 476 477 478
	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);
479 480
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
481 482 483 484 485 486 487
	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);
488 489
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
490 491 492 493 494 495 496
	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);
497 498
	if(device->pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
		fmtex->Samples.wValidBitsPerSample = device->pwfx->wBitsPerSample;
499 500 501 502 503 504 505 506
	err = DSOUND_ReopenDevice(device, FALSE);
	if(SUCCEEDED(err))
		goto opened;

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

opened:
507 508 509 510
	err = DSOUND_PrimaryOpen(device);
	if (err != DS_OK) {
		WARN("DSOUND_PrimaryOpen failed\n");
		goto done;
511 512
	}

513
	if (passed_fmt->nSamplesPerSec/100 != device->pwfx->nSamplesPerSec/100 && forced && device->buffer)
514 515
	{
		DSOUND_PrimaryClose(device);
516
		device->pwfx->nSamplesPerSec = passed_fmt->nSamplesPerSec;
517
		err = DSOUND_ReopenDevice(device, TRUE);
518
		if (FAILED(err))
519 520 521
			WARN("DSOUND_ReopenDevice(2) failed: %08x\n", err);
		else if (FAILED((err = DSOUND_PrimaryOpen(device))))
			WARN("DSOUND_PrimaryOpen(2) failed: %08x\n", err);
522 523
	}

524 525 526 527 528 529
	device->mix_buffer_len = DSOUND_bufpos_to_mixpos(device, device->buflen);
	device->mix_buffer = HeapReAlloc(GetProcessHeap(), 0, device->mix_buffer, device->mix_buffer_len);
	FillMemory(device->mix_buffer, device->mix_buffer_len, 0);
	device->mixfunction = mixfunctions[device->pwfx->wBitsPerSample/8 - 1];
	device->normfunction = normfunctions[device->pwfx->wBitsPerSample/8 - 1];

530 531 532
	if (old_fmt->nSamplesPerSec != device->pwfx->nSamplesPerSec ||
			old_fmt->wBitsPerSample != device->pwfx->wBitsPerSample ||
			old_fmt->nChannels != device->pwfx->nChannels) {
533 534
		IDirectSoundBufferImpl** dsb = device->buffers;
		for (i = 0; i < device->nrofbuffers; i++, dsb++) {
535
			/* **** */
536
			RtlAcquireResourceExclusive(&(*dsb)->lock, TRUE);
537

538 539
			(*dsb)->freqAdjust = ((DWORD64)(*dsb)->freq << DSOUND_FREQSHIFT) / device->pwfx->nSamplesPerSec;
			DSOUND_RecalcFormat((*dsb));
540
			(*dsb)->primary_mixpos = 0;
541

542
			RtlReleaseResource(&(*dsb)->lock);
543 544 545 546
			/* **** */
		}
	}

547
done:
548 549
	LeaveCriticalSection(&(device->mixlock));
	RtlReleaseResource(&(device->buffer_list_lock));
550 551
	/* **** */

552
	HeapFree(GetProcessHeap(), 0, old_fmt);
553 554 555
	return err;
}

556 557 558
/*******************************************************************************
 *		PrimaryBuffer
 */
559 560 561 562 563 564
static inline IDirectSoundBufferImpl *impl_from_IDirectSoundBuffer(IDirectSoundBuffer *iface)
{
    /* IDirectSoundBuffer and IDirectSoundBuffer8 use the same iface. */
    return CONTAINING_RECORD(iface, IDirectSoundBufferImpl, IDirectSoundBuffer8_iface);
}

565 566 567
/* This sets this format for the primary buffer only */
static HRESULT WINAPI PrimaryBufferImpl_SetFormat(IDirectSoundBuffer *iface,
        const WAVEFORMATEX *wfex)
568
{
569
    IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
570
    TRACE("(%p,%p)\n", iface, wfex);
571
    return primarybuffer_SetFormat(This->device, wfex);
572 573
}

574 575
static HRESULT WINAPI PrimaryBufferImpl_SetVolume(IDirectSoundBuffer *iface, LONG vol)
{
576 577 578 579 580
	IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
	DirectSoundDevice *device = This->device;
	HRESULT hr;
	float lvol, rvol;

581
	TRACE("(%p,%d)\n", iface, vol);
582

583
	if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
584
		WARN("control unavailable\n");
585
		return DSERR_CONTROLUNAVAIL;
586
	}
587

588
	if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN)) {
589
		WARN("invalid parameter: vol = %d\n", vol);
590
		return DSERR_INVALIDPARAM;
591
	}
592 593

	/* **** */
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
	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));
615

616 617
	DSOUND_AmpFactorToVolPan(&device->volpan);
	if (vol != device->volpan.lVolume) {
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
		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;
			}
		}
637
	}
638

639
	LeaveCriticalSection(&(device->mixlock));
640 641
	/* **** */

642
	return DS_OK;
643 644
}

645 646
static HRESULT WINAPI PrimaryBufferImpl_GetVolume(IDirectSoundBuffer *iface, LONG *vol)
{
647 648 649 650
	IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
	DirectSoundDevice *device = This->device;
	float lvol, rvol;
	HRESULT hr;
651
	TRACE("(%p,%p)\n", iface, vol);
652

653
	if (!(This->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
654 655 656 657
		WARN("control unavailable\n");
		return DSERR_CONTROLUNAVAIL;
	}

658 659
	if (vol == NULL) {
		WARN("invalid parameter: vol = NULL\n");
660
		return DSERR_INVALIDPARAM;
661
	}
662

663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
	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));

685 686 687
	DSOUND_AmpFactorToVolPan(&device->volpan);
	*vol = device->volpan.lVolume;

688 689
	LeaveCriticalSection(&device->mixlock);

690 691 692
	return DS_OK;
}

693 694
static HRESULT WINAPI PrimaryBufferImpl_SetFrequency(IDirectSoundBuffer *iface, DWORD freq)
{
695
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
696
	TRACE("(%p,%d)\n",This,freq);
697 698

	/* You cannot set the frequency of the primary buffer */
699
	WARN("control unavailable\n");
700 701 702
	return DSERR_CONTROLUNAVAIL;
}

703 704 705
static HRESULT WINAPI PrimaryBufferImpl_Play(IDirectSoundBuffer *iface, DWORD reserved1,
        DWORD reserved2, DWORD flags)
{
706 707
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
        DirectSoundDevice *device = This->device;
708
	TRACE("(%p,%08x,%08x,%08x)\n", iface, reserved1, reserved2, flags);
709

710
	if (!(flags & DSBPLAY_LOOPING)) {
711
		WARN("invalid parameter: flags = %08x\n", flags);
712
		return DSERR_INVALIDPARAM;
713
	}
714 715

	/* **** */
716
	EnterCriticalSection(&(device->mixlock));
717

718 719 720 721
	if (device->state == STATE_STOPPED)
		device->state = STATE_STARTING;
	else if (device->state == STATE_STOPPING)
		device->state = STATE_PLAYING;
722

723
	LeaveCriticalSection(&(device->mixlock));
724 725 726 727 728
	/* **** */

	return DS_OK;
}

729
static HRESULT WINAPI PrimaryBufferImpl_Stop(IDirectSoundBuffer *iface)
730
{
731 732
        IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
        DirectSoundDevice *device = This->device;
733
	TRACE("(%p)\n", iface);
734 735

	/* **** */
736
	EnterCriticalSection(&(device->mixlock));
737

738 739 740 741
	if (device->state == STATE_PLAYING)
		device->state = STATE_STOPPING;
	else if (device->state == STATE_STARTING)
		device->state = STATE_STOPPED;
742

743
	LeaveCriticalSection(&(device->mixlock));
744 745 746 747 748
	/* **** */

	return DS_OK;
}

749
static ULONG WINAPI PrimaryBufferImpl_AddRef(IDirectSoundBuffer *iface)
750
{
751
    IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
752
    ULONG ref = InterlockedIncrement(&(This->ref));
753
    TRACE("(%p) ref was %d\n", This, ref - 1);
754 755
    if(ref == 1)
        InterlockedIncrement(&This->numIfaces);
756
    return ref;
757
}
758

759 760 761 762 763 764 765
void primarybuffer_destroy(IDirectSoundBufferImpl *This)
{
    This->device->primary = NULL;
    HeapFree(GetProcessHeap(), 0, This);
    TRACE("(%p) released\n", This);
}

766
static ULONG WINAPI PrimaryBufferImpl_Release(IDirectSoundBuffer *iface)
767
{
768
    IDirectSoundBufferImpl *This = impl_from_IDirectSoundBuffer(iface);
769
    DWORD ref = InterlockedDecrement(&(This->ref));
770
    TRACE("(%p) ref was %d\n", This, ref + 1);
771

772 773
    if (!ref && !InterlockedDecrement(&This->numIfaces))
        primarybuffer_destroy(This);
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;
}