mixer.c 28.5 KB
Newer Older
1 2 3 4 5
/*  			DirectSound
 *
 * Copyright 1998 Marcus Meissner
 * Copyright 1998 Rob Riggs
 * Copyright 2000-2002 TransGaming Technologies, Inc.
6
 * Copyright 2007 Peter Dons Tychsen
7
 * Copyright 2007 Maarten Lankhorst
8
 * Copyright 2011 Owen Rudge for CodeWeavers
9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * 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
22
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 24 25
 */

#include <assert.h>
26
#include <stdarg.h>
27 28
#include <math.h>	/* Insomnia - pow() function */

29
#define COBJMACROS
30

31 32 33
#include "windef.h"
#include "winbase.h"
#include "mmsystem.h"
34 35
#include "wingdi.h"
#include "mmreg.h"
36
#include "winternl.h"
37 38
#include "wine/debug.h"
#include "dsound.h"
39 40
#include "ks.h"
#include "ksmedia.h"
41
#include "dsound_private.h"
42
#include "fir.h"
43 44 45 46 47 48

WINE_DEFAULT_DEBUG_CHANNEL(dsound);

void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
{
	double temp;
49
	TRACE("(%p)\n",volpan);
50

51
	TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
52 53 54 55
	/* the AmpFactors are expressed in 16.16 fixed point */

	/* FIXME: use calculated vol and pan ampfactors */
	temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
56
	volpan->dwTotalAmpFactor[0] = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
57
	temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
58
	volpan->dwTotalAmpFactor[1] = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
59

60
	TRACE("left = %x, right = %x\n", volpan->dwTotalAmpFactor[0], volpan->dwTotalAmpFactor[1]);
61 62
}

63 64 65 66 67
void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
{
    double left,right;
    TRACE("(%p)\n",volpan);

68 69
    TRACE("left=%x, right=%x\n",volpan->dwTotalAmpFactor[0],volpan->dwTotalAmpFactor[1]);
    if (volpan->dwTotalAmpFactor[0]==0)
70 71
        left=-10000;
    else
72 73
        left=600 * log(((double)volpan->dwTotalAmpFactor[0]) / 0xffff) / log(2);
    if (volpan->dwTotalAmpFactor[1]==0)
74 75
        right=-10000;
    else
76
        right=600 * log(((double)volpan->dwTotalAmpFactor[1]) / 0xffff) / log(2);
77
    if (left<right)
78
        volpan->lVolume=right;
79
    else
80
        volpan->lVolume=left;
81 82
    if (volpan->lVolume < -10000)
        volpan->lVolume=-10000;
83
    volpan->lPan=right-left;
84 85 86
    if (volpan->lPan < -10000)
        volpan->lPan=-10000;

87
    TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
88 89
}

90 91 92 93 94 95
/**
 * Recalculate the size for temporary buffer, and new writelead
 * Should be called when one of the following things occur:
 * - Primary buffer format is changed
 * - This buffer format (frequency) is changed
 */
96 97
void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
{
98 99
	DWORD ichannels = dsb->pwfx->nChannels;
	DWORD ochannels = dsb->device->pwfx->nChannels;
100 101
	WAVEFORMATEXTENSIBLE *pwfxe;
	BOOL ieee = FALSE;
102

103
	TRACE("(%p)\n",dsb);
104

105
	pwfxe = (WAVEFORMATEXTENSIBLE *) dsb->pwfx;
106 107
	dsb->freqAdjustNum = dsb->freq;
	dsb->freqAdjustDen = dsb->device->pwfx->nSamplesPerSec;
108 109 110 111 112

	if ((pwfxe->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) || ((pwfxe->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
	    && (IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))))
		ieee = TRUE;

113 114 115 116 117 118 119
	/**
	 * Recalculate FIR step and gain.
	 *
	 * firstep says how many points of the FIR exist per one
	 * sample in the secondary buffer. firgain specifies what
	 * to multiply the FIR output by in order to attenuate it correctly.
	 */
120
	if (dsb->freqAdjustNum / dsb->freqAdjustDen > 0) {
121 122 123 124
		/**
		 * Yes, round it a bit to make sure that the
		 * linear interpolation factor never changes.
		 */
125
		dsb->firstep = fir_step * dsb->freqAdjustDen / dsb->freqAdjustNum;
126 127 128 129 130
	} else {
		dsb->firstep = fir_step;
	}
	dsb->firgain = (float)dsb->firstep / fir_step;

131
	/* calculate the 10ms write lead */
132
	dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
133

134
	dsb->freqAccNum = 0;
135

136
	dsb->get_aux = ieee ? getbpp[4] : getbpp[dsb->pwfx->wBitsPerSample/8 - 1];
137
	dsb->put_aux = putieee32;
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152

	dsb->get = dsb->get_aux;
	dsb->put = dsb->put_aux;

	if (ichannels == ochannels)
	{
		dsb->mix_channels = ichannels;
		if (ichannels > 32) {
			FIXME("Copying %u channels is unsupported, limiting to first 32\n", ichannels);
			dsb->mix_channels = 32;
		}
	}
	else if (ichannels == 1)
	{
		dsb->mix_channels = 1;
153 154 155 156 157

		if (ochannels == 2)
			dsb->put = put_mono2stereo;
		else if (ochannels == 4)
			dsb->put = put_mono2quad;
158 159
		else if (ochannels == 6)
			dsb->put = put_mono2surround51;
160 161 162 163 164 165
	}
	else if (ochannels == 1)
	{
		dsb->mix_channels = 1;
		dsb->get = get_mono;
	}
166 167 168 169 170
	else if (ichannels == 2 && ochannels == 4)
	{
		dsb->mix_channels = 2;
		dsb->put = put_stereo2quad;
	}
171 172 173 174 175
	else if (ichannels == 2 && ochannels == 6)
	{
		dsb->mix_channels = 2;
		dsb->put = put_stereo2surround51;
	}
176 177 178 179 180 181
	else
	{
		if (ichannels > 2)
			FIXME("Conversion from %u to %u channels is not implemented, falling back to stereo\n", ichannels, ochannels);
		dsb->mix_channels = 2;
	}
182 183
}

184 185 186 187 188 189 190 191
/**
 * Check for application callback requests for when the play position
 * reaches certain points.
 *
 * The offsets that will be triggered will be those between the recorded
 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
 * beyond that position.
 */
192
void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
193
{
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    int first, left, right, check;

    if(dsb->nrofnotifies == 0)
        return;

    if(dsb->state == STATE_STOPPED){
        TRACE("Stopped...\n");
        /* DSBPN_OFFSETSTOP notifies are always at the start of the sorted array */
        for(left = 0; left < dsb->nrofnotifies; ++left){
            if(dsb->notifies[left].dwOffset != DSBPN_OFFSETSTOP)
                break;

            TRACE("Signalling %p\n", dsb->notifies[left].hEventNotify);
            SetEvent(dsb->notifies[left].hEventNotify);
        }
        return;
    }

    for(first = 0; first < dsb->nrofnotifies && dsb->notifies[first].dwOffset == DSBPN_OFFSETSTOP; ++first)
        ;

    if(first == dsb->nrofnotifies)
        return;

    check = left = first;
    right = dsb->nrofnotifies - 1;

    /* find leftmost notify that is greater than playpos */
    while(left != right){
        check = left + (right - left) / 2;
        if(dsb->notifies[check].dwOffset < playpos)
            left = check + 1;
        else if(dsb->notifies[check].dwOffset > playpos)
            right = check;
        else{
            left = check;
            break;
        }
    }

234 235 236 237
    TRACE("Not stopped: first notify: %u (%u), left notify: %u (%u), range: [%u,%u)\n",
            first, dsb->notifies[first].dwOffset,
            left, dsb->notifies[left].dwOffset,
            playpos, (playpos + len) % dsb->buflen);
238 239

    /* send notifications in range */
240 241 242 243
    if(dsb->notifies[left].dwOffset >= playpos){
        for(check = left; check < dsb->nrofnotifies; ++check){
            if(dsb->notifies[check].dwOffset >= playpos + len)
                break;
244

245 246 247
            TRACE("Signalling %p (%u)\n", dsb->notifies[check].hEventNotify, dsb->notifies[check].dwOffset);
            SetEvent(dsb->notifies[check].hEventNotify);
        }
248 249 250 251 252 253 254 255 256 257 258
    }

    if(playpos + len > dsb->buflen){
        for(check = first; check < left; ++check){
            if(dsb->notifies[check].dwOffset >= (playpos + len) % dsb->buflen)
                break;

            TRACE("Signalling %p (%u)\n", dsb->notifies[check].hEventNotify, dsb->notifies[check].dwOffset);
            SetEvent(dsb->notifies[check].hEventNotify);
        }
    }
259 260
}

261 262 263 264 265 266 267 268
static inline float get_current_sample(const IDirectSoundBufferImpl *dsb,
        DWORD mixpos, DWORD channel)
{
    if (mixpos >= dsb->buflen && !(dsb->playflags & DSBPLAY_LOOPING))
        return 0.0f;
    return dsb->get(dsb, mixpos % dsb->buflen, channel);
}

269
static UINT cp_fields_noresample(IDirectSoundBufferImpl *dsb, UINT count)
270 271
{
    UINT istride = dsb->pwfx->nBlockAlign;
272
    UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
273 274 275 276 277 278 279 280
    DWORD channel, i;
    for (i = 0; i < count; i++)
        for (channel = 0; channel < dsb->mix_channels; channel++)
            dsb->put(dsb, i * ostride, channel, get_current_sample(dsb,
                    dsb->sec_mixpos + i * istride, channel));
    return count;
}

281
static UINT cp_fields_resample(IDirectSoundBufferImpl *dsb, UINT count, LONG64 *freqAccNum)
282
{
283 284
    UINT i, channel;
    UINT istride = dsb->pwfx->nBlockAlign;
285
    UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
286

287 288
    LONG64 freqAcc_start = *freqAccNum;
    LONG64 freqAcc_end = freqAcc_start + count * dsb->freqAdjustNum;
289 290
    UINT dsbfirstep = dsb->firstep;
    UINT channels = dsb->mix_channels;
291
    UINT max_ipos = (freqAcc_start + count * dsb->freqAdjustNum) / dsb->freqAdjustDen;
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312

    UINT fir_cachesize = (fir_len + dsbfirstep - 2) / dsbfirstep;
    UINT required_input = max_ipos + fir_cachesize;

    float* intermediate = HeapAlloc(GetProcessHeap(), 0,
            sizeof(float) * required_input * channels);

    float* fir_copy = HeapAlloc(GetProcessHeap(), 0,
            sizeof(float) * fir_cachesize);

    /* Important: this buffer MUST be non-interleaved
     * if you want -msse3 to have any effect.
     * This is good for CPU cache effects, too.
     */
    float* itmp = intermediate;
    for (channel = 0; channel < channels; channel++)
        for (i = 0; i < required_input; i++)
            *(itmp++) = get_current_sample(dsb,
                    dsb->sec_mixpos + i * istride, channel);

    for(i = 0; i < count; ++i) {
313 314
        UINT int_fir_steps = (freqAcc_start + i * dsb->freqAdjustNum) * dsbfirstep / dsb->freqAdjustDen;
        float total_fir_steps = (freqAcc_start + i * dsb->freqAdjustNum) * dsbfirstep / (float)dsb->freqAdjustDen;
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
        UINT ipos = int_fir_steps / dsbfirstep;

        UINT idx = (ipos + 1) * dsbfirstep - int_fir_steps - 1;
        float rem = int_fir_steps + 1.0 - total_fir_steps;

        int fir_used = 0;
        while (idx < fir_len - 1) {
            fir_copy[fir_used++] = fir[idx] * (1.0 - rem) + fir[idx + 1] * rem;
            idx += dsb->firstep;
        }

        assert(fir_used <= fir_cachesize);
        assert(ipos + fir_used <= required_input);

        for (channel = 0; channel < dsb->mix_channels; channel++) {
            int j;
            float sum = 0.0;
            float* cache = &intermediate[channel * required_input + ipos];
            for (j = 0; j < fir_used; j++)
                sum += fir_copy[j] * cache[j];
            dsb->put(dsb, i * ostride, channel, sum * dsb->firgain);
        }
337
    }
338

339
    *freqAccNum = freqAcc_end % dsb->freqAdjustDen;
340 341 342 343 344 345 346

    HeapFree(GetProcessHeap(), 0, fir_copy);
    HeapFree(GetProcessHeap(), 0, intermediate);

    return max_ipos;
}

347
static void cp_fields(IDirectSoundBufferImpl *dsb, UINT count, LONG64 *freqAccNum)
348 349 350
{
    DWORD ipos, adv;

351 352
    if (dsb->freqAdjustNum == dsb->freqAdjustDen)
        adv = cp_fields_noresample(dsb, count); /* *freqAccNum is unmodified */
353
    else
354
        adv = cp_fields_resample(dsb, count, freqAccNum);
355 356

    ipos = dsb->sec_mixpos + adv * dsb->pwfx->nBlockAlign;
357 358 359 360 361 362 363 364 365 366
    if (ipos >= dsb->buflen) {
        if (dsb->playflags & DSBPLAY_LOOPING)
            ipos %= dsb->buflen;
        else {
            ipos = 0;
            dsb->state = STATE_STOPPED;
        }
    }

    dsb->sec_mixpos = ipos;
367 368
}

369
/**
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
 * Calculate the distance between two buffer offsets, taking wraparound
 * into account.
 */
static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
{
/* If these asserts fail, the problem is not here, but in the underlying code */
	assert(ptr1 < buflen);
	assert(ptr2 < buflen);
	if (ptr1 >= ptr2) {
		return ptr1 - ptr2;
	} else {
		return buflen + ptr1 - ptr2;
	}
}
/**
 * Mix at most the given amount of data into the allocated temporary buffer
 * of the given secondary buffer, starting from the dsb's first currently
 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
 * and bits-per-sample so that it is ideal for the primary buffer.
 * Doesn't perform any mixing - this is a straight copy/convert operation.
390 391
 *
 * dsb = the secondary buffer
392 393
 * writepos = Starting position of changed buffer
 * len = number of bytes to resample from writepos
394
 *
395
 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
396
 */
397
static void DSOUND_MixToTemporary(IDirectSoundBufferImpl *dsb, DWORD frames)
398
{
399
	UINT size_bytes = frames * sizeof(float) * dsb->device->pwfx->nChannels;
400 401
	HRESULT hr;
	int i;
402

403
	if (dsb->device->tmp_buffer_len < size_bytes || !dsb->device->tmp_buffer)
404
	{
405
		dsb->device->tmp_buffer_len = size_bytes;
406
		if (dsb->device->tmp_buffer)
407
			dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, size_bytes);
408
		else
409
			dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, size_bytes);
410
	}
411

412
	cp_fields(dsb, frames, &dsb->freqAccNum);
413 414 415 416 417 418 419 420 421 422 423 424

	if (size_bytes > 0) {
		for (i = 0; i < dsb->num_filters; i++) {
			if (dsb->filters[i].inplace) {
				hr = IMediaObjectInPlace_Process(dsb->filters[i].inplace, size_bytes, (BYTE*)dsb->device->tmp_buffer, 0, DMO_INPLACE_NORMAL);

				if (FAILED(hr))
					WARN("IMediaObjectInPlace_Process failed for filter %u\n", i);
			} else
				WARN("filter %u has no inplace object - unsupported\n", i);
		}
	}
425 426
}

427
static void DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT frames)
428
{
429
	INT	i;
430
	float vols[DS_MAX_CHANNELS];
431
	UINT channels = dsb->device->pwfx->nChannels, chan;
432

433
	TRACE("(%p,%d)\n",dsb,frames);
434 435
	TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalAmpFactor[0],
		dsb->volpan.dwTotalAmpFactor[1]);
436

437 438 439
	if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
	    (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
	     !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
440
		return; /* Nothing to do */
441

442
	if (channels > DS_MAX_CHANNELS)
443
	{
444 445
		FIXME("There is no support for %u channels\n", channels);
		return;
446 447
	}

448 449 450
	for (i = 0; i < channels; ++i)
		vols[i] = dsb->volpan.dwTotalAmpFactor[i] / ((float)0xFFFF);

451 452
	for(i = 0; i < frames; ++i){
		for(chan = 0; chan < channels; ++chan){
453
			dsb->device->tmp_buffer[i * channels + chan] *= vols[chan];
454
		}
455 456 457
	}
}

458 459 460 461 462 463 464 465 466 467 468 469 470
/**
 * Mix (at most) the given number of bytes into the given position of the
 * device buffer, from the secondary buffer "dsb" (starting at the current
 * mix position for that buffer).
 *
 * Returns the number of bytes actually mixed into the device buffer. This
 * will match fraglen unless the end of the secondary buffer is reached
 * (and it is not looping).
 *
 * dsb  = the secondary buffer to mix from
 * writepos = position (offset) in device buffer to write at
 * fraglen = number of bytes to mix
 */
471 472
static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
{
473
	INT len = fraglen;
474
	float *ibuf;
475
	DWORD oldpos;
476
	UINT frames = fraglen / dsb->device->pwfx->nBlockAlign;
477

478
	TRACE("sec_mixpos=%d/%d\n", dsb->sec_mixpos, dsb->buflen);
479
	TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
480

Robert Reif's avatar
Robert Reif committed
481 482
	if (len % dsb->device->pwfx->nBlockAlign) {
		INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
483
		ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
484
		len -= len % nBlockAlign; /* data alignment */
485
	}
486

487
	/* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
488 489
	oldpos = dsb->sec_mixpos;

490
	DSOUND_MixToTemporary(dsb, frames);
491
	ibuf = dsb->device->tmp_buffer;
492

493
	/* Apply volume if needed */
494
	DSOUND_MixerVol(dsb, frames);
495

496
	mixieee32(ibuf, dsb->device->mix_buffer, frames * dsb->device->pwfx->nChannels);
497

498 499 500
	/* check for notification positions */
	if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
	    dsb->state != STATE_STARTING) {
501
		INT ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
502
		DSOUND_CheckEvent(dsb, oldpos, ilen);
503 504 505 506 507
	}

	return len;
}

508 509 510 511 512
/**
 * Mix some frames from the given secondary buffer "dsb" into the device
 * primary buffer.
 *
 * dsb = the secondary buffer
513
 * playpos = the current play position in the device buffer (primary buffer)
514 515 516 517 518 519
 * writepos = the current safe-to-write position in the device buffer
 * mixlen = the maximum number of bytes in the primary buffer to mix, from the
 *          current writepos.
 *
 * Returns: the number of bytes beyond the writepos that were mixed.
 */
520
static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD mixlen)
521
{
522
	DWORD primary_done = 0;
523

524
	TRACE("(%p,%d,%d)\n",dsb,writepos,mixlen);
525
	TRACE("writepos=%d, mixlen=%d\n", writepos, mixlen);
526
	TRACE("looping=%d, leadin=%d\n", dsb->playflags, dsb->leadin);
527 528

	/* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
529 530 531 532 533 534 535
	/* FIXME: Is this needed? */
	if (dsb->leadin && dsb->state == STATE_STARTING) {
		if (mixlen > 2 * dsb->device->fraglen) {
			primary_done = mixlen - 2 * dsb->device->fraglen;
			mixlen = 2 * dsb->device->fraglen;
			writepos += primary_done;
			dsb->sec_mixpos += (primary_done / dsb->device->pwfx->nBlockAlign) *
536
				dsb->pwfx->nBlockAlign * dsb->freqAdjustNum / dsb->freqAdjustDen;
537 538
		}
	}
539

540
	dsb->leadin = FALSE;
541

542
	TRACE("mixlen (primary) = %i\n", mixlen);
543 544 545 546

	/* First try to mix to the end of the buffer if possible
	 * Theoretically it would allow for better optimization
	*/
547
	primary_done += DSOUND_MixInBuffer(dsb, writepos, mixlen);
548

549
	TRACE("total mixed data=%d\n", primary_done);
550

551 552
	/* Report back the total prebuffered amount for this buffer */
	return primary_done;
553 554
}

555 556 557 558 559 560 561 562 563
/**
 * For a DirectSoundDevice, go through all the currently playing buffers and
 * mix them in to the device buffer.
 *
 * writepos = the current safe-to-write position in the primary buffer
 * mixlen = the maximum amount to mix into the primary buffer
 *          (beyond the current writepos)
 * recover = true if the sound device may have been reset and the write
 *           position in the device buffer changed
564
 * all_stopped = reports back if all buffers have stopped
565 566 567
 *
 * Returns:  the length beyond the writepos that was mixed to.
 */
568

569
static void DSOUND_MixToPrimary(const DirectSoundDevice *device, DWORD writepos, DWORD mixlen, BOOL recover, BOOL *all_stopped)
570
{
571
	INT i;
572 573
	IDirectSoundBufferImpl	*dsb;

574 575 576
	/* unless we find a running buffer, all have stopped */
	*all_stopped = TRUE;

577
	TRACE("(%d,%d,%d)\n", writepos, mixlen, recover);
578 579
	for (i = 0; i < device->nrofbuffers; i++) {
		dsb = device->buffers[i];
580

581 582
		TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);

583
		if (dsb->buflen && dsb->state) {
584
			TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
585
			RtlAcquireResourceShared(&dsb->lock, TRUE);
586
			/* if buffer is stopping it is stopped now */
587 588
			if (dsb->state == STATE_STOPPING) {
				dsb->state = STATE_STOPPED;
589
				DSOUND_CheckEvent(dsb, 0, 0);
590
			} else if (dsb->state != STATE_STOPPED) {
591 592

				/* if the buffer was starting, it must be playing now */
593 594
				if (dsb->state == STATE_STARTING)
					dsb->state = STATE_PLAYING;
595

596
				/* mix next buffer into the main buffer */
597
				DSOUND_MixOne(dsb, writepos, mixlen);
598 599

				*all_stopped = FALSE;
600
			}
601
			RtlReleaseResource(&dsb->lock);
602 603 604 605
		}
	}
}

606 607 608 609 610 611 612 613 614 615 616
/**
 * Add buffers to the emulated wave device system.
 *
 * device = The current dsound playback device
 * force = If TRUE, the function will buffer up as many frags as possible,
 *         even though and will ignore the actual state of the primary buffer.
 *
 * Returns:  None
 */

static void DSOUND_WaveQueue(DirectSoundDevice *device, BOOL force)
617
{
618
	DWORD prebuf_frames, prebuf_bytes, read_offs_bytes;
619 620 621
	BYTE *buffer;
	HRESULT hr;

622
	TRACE("(%p)\n", device);
623

624
	read_offs_bytes = (device->playing_offs_bytes + device->in_mmdev_bytes) % device->buflen;
625

626 627
	TRACE("read_offs_bytes = %u, playing_offs_bytes = %u, in_mmdev_bytes: %u, prebuf = %u\n",
		read_offs_bytes, device->playing_offs_bytes, device->in_mmdev_bytes, device->prebuf);
628

629 630
	if (!force)
	{
631 632 633 634
		if(device->mixpos < device->playing_offs_bytes)
			prebuf_bytes = device->mixpos + device->buflen - device->playing_offs_bytes;
		else
			prebuf_bytes = device->mixpos - device->playing_offs_bytes;
635
	}
636
	else
637
		/* buffer the maximum amount of frags */
638
		prebuf_bytes = device->prebuf * device->fraglen;
639

640
	/* limit to the queue we have left */
641 642
	if(device->in_mmdev_bytes + prebuf_bytes > device->prebuf * device->fraglen)
		prebuf_bytes = device->prebuf * device->fraglen - device->in_mmdev_bytes;
643

644
	TRACE("prebuf_bytes = %u\n", prebuf_bytes);
645

646
	if(!prebuf_bytes)
647 648
		return;

649 650 651 652 653 654 655 656
	if(prebuf_bytes + read_offs_bytes > device->buflen){
		DWORD chunk_bytes = device->buflen - read_offs_bytes;
		prebuf_frames = chunk_bytes / device->pwfx->nBlockAlign;
		prebuf_bytes -= chunk_bytes;
	}else{
		prebuf_frames = prebuf_bytes / device->pwfx->nBlockAlign;
		prebuf_bytes = 0;
	}
657 658 659 660 661 662 663

	hr = IAudioRenderClient_GetBuffer(device->render, prebuf_frames, &buffer);
	if(FAILED(hr)){
		WARN("GetBuffer failed: %08x\n", hr);
		return;
	}

664
	memcpy(buffer, device->buffer + read_offs_bytes,
665
			prebuf_frames * device->pwfx->nBlockAlign);
666

667 668 669 670
	hr = IAudioRenderClient_ReleaseBuffer(device->render, prebuf_frames, 0);
	if(FAILED(hr)){
		WARN("ReleaseBuffer failed: %08x\n", hr);
		return;
671 672
	}

673 674
	device->in_mmdev_bytes += prebuf_frames * device->pwfx->nBlockAlign;

675
	/* check if anything wrapped */
676 677
	if(prebuf_bytes > 0){
		prebuf_frames = prebuf_bytes / device->pwfx->nBlockAlign;
678 679 680 681 682 683 684 685 686 687 688 689 690 691

		hr = IAudioRenderClient_GetBuffer(device->render, prebuf_frames, &buffer);
		if(FAILED(hr)){
			WARN("GetBuffer failed: %08x\n", hr);
			return;
		}

		memcpy(buffer, device->buffer, prebuf_frames * device->pwfx->nBlockAlign);

		hr = IAudioRenderClient_ReleaseBuffer(device->render, prebuf_frames, 0);
		if(FAILED(hr)){
			WARN("ReleaseBuffer failed: %08x\n", hr);
			return;
		}
692
		device->in_mmdev_bytes += prebuf_frames * device->pwfx->nBlockAlign;
693
	}
694

695
	TRACE("in_mmdev_bytes now = %i\n", device->in_mmdev_bytes);
696
}
697

698 699 700 701
/**
 * Perform mixing for a Direct Sound device. That is, go through all the
 * secondary buffers (the sound bites currently playing) and mix them in
 * to the primary buffer (the device buffer).
702 703 704 705 706 707 708 709
 *
 * The mixing procedure goes:
 *
 * secondary->buffer (secondary format)
 *   =[Resample]=> device->tmp_buffer (float format)
 *   =[Volume]=> device->tmp_buffer (float format)
 *   =[Mix]=> device->mix_buffer (float format)
 *   =[Reformat]=> device->buffer (device format)
710
 */
711
static void DSOUND_PerformMix(DirectSoundDevice *device)
712
{
713
	UINT32 pad, to_mix_frags, to_mix_bytes;
714 715
	HRESULT hr;

716
	TRACE("(%p)\n", device);
717

718
	/* **** */
719 720
	EnterCriticalSection(&device->mixlock);

721
	hr = IAudioClient_GetCurrentPadding(device->client, &pad);
722
	if(FAILED(hr)){
723 724
		WARN("GetCurrentPadding failed: %08x\n", hr);
		LeaveCriticalSection(&device->mixlock);
725 726 727
		return;
	}

728 729 730
	to_mix_frags = device->prebuf - (pad * device->pwfx->nBlockAlign + device->fraglen - 1) / device->fraglen;

	to_mix_bytes = to_mix_frags * device->fraglen;
731

732 733 734 735
	if(device->in_mmdev_bytes > 0){
		DWORD delta_bytes = min(to_mix_bytes, device->in_mmdev_bytes);
		device->in_mmdev_bytes -= delta_bytes;
		device->playing_offs_bytes += delta_bytes;
736
		device->playing_offs_bytes %= device->buflen;
737
	}
738

739
	if (device->priolevel != DSSCL_WRITEPRIMARY) {
740
		BOOL recover = FALSE, all_stopped = FALSE;
741
		DWORD playpos, writepos, writelead, maxq, prebuff_max, prebuff_left, size1, size2;
742 743 744 745 746 747 748 749 750 751
		LPVOID buf1, buf2;
		int nfiller;

		/* the sound of silence */
		nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;

		/* get the position in the primary buffer */
		if (DSOUND_PrimaryGetPosition(device, &playpos, &writepos) != 0){
			LeaveCriticalSection(&(device->mixlock));
			return;
752
		}
753

754
		TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
755
			playpos,writepos,device->playpos,device->mixpos,device->buflen);
756
		assert(device->playpos < device->buflen);
757

758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
		/* calc maximum prebuff */
		prebuff_max = (device->prebuf * device->fraglen);

		/* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
		prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
		writelead = DSOUND_BufPtrDiff(device->buflen, writepos, playpos);

		/* check for underrun. underrun occurs when the write position passes the mix position
		 * also wipe out just-played sound data */
		if((prebuff_left > prebuff_max) || (device->state == STATE_STOPPED) || (device->state == STATE_STARTING)){
			if (device->state == STATE_STOPPING || device->state == STATE_PLAYING)
				WARN("Probable buffer underrun\n");
			else TRACE("Buffer starting or buffer underrun\n");

			/* recover mixing for all buffers */
			recover = TRUE;

			/* reset mix position to write position */
			device->mixpos = writepos;

			ZeroMemory(device->buffer, device->buflen);
		} else if (playpos < device->playpos) {
780 781 782 783 784 785 786 787
			buf1 = device->buffer + device->playpos;
			buf2 = device->buffer;
			size1 = device->buflen - device->playpos;
			size2 = playpos;
			FillMemory(buf1, size1, nfiller);
			if (playpos && (!buf2 || !size2))
				FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__, device->playpos, device->mixpos, playpos, writepos);
			FillMemory(buf2, size2, nfiller);
788
		} else {
789 790 791 792 793
			buf1 = device->buffer + device->playpos;
			buf2 = NULL;
			size1 = playpos - device->playpos;
			size2 = 0;
			FillMemory(buf1, size1, nfiller);
794
		}
795
		device->playpos = playpos;
796

797 798 799 800 801 802
		/* find the maximum we can prebuffer from current write position */
		maxq = (writelead < prebuff_max) ? (prebuff_max - writelead) : 0;

		TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
			prebuff_left, device->prebuf, device->fraglen, prebuff_max, writelead);

803 804
		ZeroMemory(device->mix_buffer, device->mix_buffer_len);

805
		/* do the mixing */
806
		DSOUND_MixToPrimary(device, writepos, maxq, recover, &all_stopped);
807

808
		if (maxq + writepos > device->buflen)
809 810
		{
			DWORD todo = device->buflen - writepos;
811 812 813
			DWORD offs_float = (todo / device->pwfx->nBlockAlign) * device->pwfx->nChannels;
			device->normfunction(device->mix_buffer, device->buffer + writepos, todo);
			device->normfunction(device->mix_buffer + offs_float, device->buffer, maxq - todo);
814 815
		}
		else
816
			device->normfunction(device->mix_buffer, device->buffer + writepos, maxq);
817

Austin English's avatar
Austin English committed
818
		/* update the mix position, taking wrap-around into account */
819
		device->mixpos = writepos + maxq;
820
		device->mixpos %= device->buflen;
821

822 823 824 825 826 827
		/* update prebuff left */
		prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);

		/* check if have a whole fragment */
		if (prebuff_left >= device->fraglen){

828
			/* update the wave queue */
829
			DSOUND_WaveQueue(device, FALSE);
830 831 832 833 834

			/* buffers are full. start playing if applicable */
			if(device->state == STATE_STARTING){
				TRACE("started primary buffer\n");
				if(DSOUND_PrimaryPlay(device) != DS_OK){
835
					WARN("DSOUND_PrimaryPlay failed\n");
836 837 838 839 840 841 842 843 844
				}
				else{
					/* we are playing now */
					device->state = STATE_PLAYING;
				}
			}

			/* buffers are full. start stopping if applicable */
			if(device->state == STATE_STOPPED){
845
				TRACE("restarting primary buffer\n");
846 847 848 849 850 851 852
				if(DSOUND_PrimaryPlay(device) != DS_OK){
					WARN("DSOUND_PrimaryPlay failed\n");
				}
				else{
					/* start stopping again. as soon as there is no more data, it will stop */
					device->state = STATE_STOPPING;
				}
853 854
			}
		}
855 856

		/* if device was stopping, its for sure stopped when all buffers have stopped */
857
		else if (all_stopped && (device->state == STATE_STOPPING)) {
858 859 860 861 862 863 864
			TRACE("All buffers have stopped. Stopping primary buffer\n");
			device->state = STATE_STOPPED;

			/* stop the primary buffer now */
			DSOUND_PrimaryStop(device);
		}

865
	} else if (device->state != STATE_STOPPED) {
866

867
		DSOUND_WaveQueue(device, TRUE);
868

869
		/* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
870 871
		if (device->state == STATE_STARTING) {
			if (DSOUND_PrimaryPlay(device) != DS_OK)
872 873
				WARN("DSOUND_PrimaryPlay failed\n");
			else
874
				device->state = STATE_PLAYING;
875
		}
876 877
		else if (device->state == STATE_STOPPING) {
			if (DSOUND_PrimaryStop(device) != DS_OK)
878 879
				WARN("DSOUND_PrimaryStop failed\n");
			else
880
				device->state = STATE_STOPPED;
881 882
		}
	}
883 884 885

	LeaveCriticalSection(&(device->mixlock));
	/* **** */
886 887
}

888
DWORD CALLBACK DSOUND_mixthread(void *p)
889
{
890 891
	DirectSoundDevice *dev = p;
	TRACE("(%p)\n", dev);
892

893 894
	while (dev->ref) {
		DWORD ret;
895

896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
		/*
		 * Some audio drivers are retarded and won't fire after being
		 * stopped, add a timeout to handle this.
		 */
		ret = WaitForSingleObject(dev->sleepev, dev->sleeptime);
		if (ret == WAIT_FAILED)
			WARN("wait returned error %u %08x!\n", GetLastError(), GetLastError());
		else if (ret != WAIT_OBJECT_0)
			WARN("wait returned %08x!\n", ret);
		if (!dev->ref)
			break;

		RtlAcquireResourceShared(&(dev->buffer_list_lock), TRUE);
		DSOUND_PerformMix(dev);
		RtlReleaseResource(&(dev->buffer_list_lock));
	}
912
	SetEvent(dev->thread_finished);
913
	return 0;
914
}