3 * Copyright 1998 Marcus Meissner
4 * Copyright 1998 Rob Riggs
5 * Copyright 2000-2002 TransGaming Technologies, Inc.
6 * Copyright 2007 Peter Dons Tychsen
7 * Copyright 2007 Maarten Lankhorst
8 * Copyright 2011 Owen Rudge for CodeWeavers
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * 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
27 #include <math.h> /* Insomnia - pow() function */
30 #define NONAMELESSSTRUCT
31 #define NONAMELESSUNION
38 #include "wine/debug.h"
42 #include "dsound_private.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
46 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
49 TRACE("(%p)\n",volpan);
51 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
52 /* the AmpFactors are expressed in 16.16 fixed point */
53 volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
54 /* FIXME: dwPan{Left|Right}AmpFactor */
56 /* FIXME: use calculated vol and pan ampfactors */
57 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
58 volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
59 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
60 volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
62 TRACE("left = %x, right = %x\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
65 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
68 TRACE("(%p)\n",volpan);
70 TRACE("left=%x, right=%x\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
71 if (volpan->dwTotalLeftAmpFactor==0)
74 left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
75 if (volpan->dwTotalRightAmpFactor==0)
78 right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
81 volpan->lVolume=right;
82 volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
87 volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
89 if (volpan->lVolume < -10000)
90 volpan->lVolume=-10000;
91 volpan->lPan=right-left;
92 if (volpan->lPan < -10000)
95 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
98 /** Convert a primary buffer position to a pointer position for device->mix_buffer
99 * device: DirectSoundDevice for which to calculate
100 * pos: Primary buffer position to converts
101 * Returns: Offset for mix_buffer
103 DWORD DSOUND_bufpos_to_mixpos(const DirectSoundDevice* device, DWORD pos)
105 DWORD ret = pos * 32 / device->pwfx->wBitsPerSample;
106 if (device->pwfx->wBitsPerSample == 32)
111 /* NOTE: Not all secpos have to always be mapped to a bufpos, other way around is always the case
112 * DWORD64 is used here because a single DWORD wouldn't be big enough to fit the freqAcc for big buffers
114 /** This function converts a 'native' sample pointer to a resampled pointer that fits for primary
115 * secmixpos is used to decide which freqAcc is needed
116 * overshot tells what the 'actual' secpos is now (optional)
118 DWORD DSOUND_secpos_to_bufpos(const IDirectSoundBufferImpl *dsb, DWORD secpos, DWORD secmixpos, DWORD* overshot)
120 DWORD64 framelen = secpos / dsb->pwfx->nBlockAlign;
121 DWORD64 freqAdjust = dsb->freqAdjust;
122 DWORD64 acc, freqAcc;
124 if (secpos < secmixpos)
125 freqAcc = dsb->freqAccNext;
126 else freqAcc = dsb->freqAcc;
127 acc = (framelen << DSOUND_FREQSHIFT) + (freqAdjust - 1 - freqAcc);
131 DWORD64 oshot = acc * freqAdjust + freqAcc;
132 assert(oshot >= framelen << DSOUND_FREQSHIFT);
133 oshot -= framelen << DSOUND_FREQSHIFT;
134 *overshot = (DWORD)oshot;
135 assert(*overshot < dsb->freqAdjust);
137 return (DWORD)acc * dsb->device->pwfx->nBlockAlign;
140 /** Convert a resampled pointer that fits for primary to a 'native' sample pointer
142 static DWORD DSOUND_bufpos_to_secpos(const IDirectSoundBufferImpl *dsb, DWORD bufpos)
144 DWORD oAdv = dsb->device->pwfx->nBlockAlign, iAdv = dsb->pwfx->nBlockAlign, pos;
148 framelen = bufpos/oAdv;
149 acc = framelen * (DWORD64)dsb->freqAdjust + (DWORD64)dsb->freqAcc;
150 acc = acc >> DSOUND_FREQSHIFT;
151 pos = (DWORD)acc * iAdv;
152 if (pos >= dsb->buflen) {
153 /* FIXME: can this happen at all? */
154 ERR("pos >= dsb->buflen: %d >= %d, capping\n", pos, dsb->buflen);
155 pos = dsb->buflen - iAdv;
158 TRACE("Converted %d/%d to %d/%d\n", bufpos, dsb->tmp_buffer_len, pos, dsb->buflen);
163 * Move freqAccNext to freqAcc, and find new values for buffer length and freqAccNext
165 static void DSOUND_RecalcFreqAcc(IDirectSoundBufferImpl *dsb)
167 if (!dsb->freqneeded) return;
168 dsb->freqAcc = dsb->freqAccNext;
169 dsb->tmp_buffer_len = DSOUND_secpos_to_bufpos(dsb, dsb->buflen, 0, &dsb->freqAccNext);
170 TRACE("New freqadjust: %04x, new buflen: %d\n", dsb->freqAccNext, dsb->tmp_buffer_len);
174 * Recalculate the size for temporary buffer, and new writelead
175 * Should be called when one of the following things occur:
176 * - Primary buffer format is changed
177 * - This buffer format (frequency) is changed
179 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
181 BOOL needremix = TRUE, needresample = (dsb->freq != dsb->device->pwfx->nSamplesPerSec);
182 DWORD bAlign = dsb->pwfx->nBlockAlign, pAlign = dsb->device->pwfx->nBlockAlign;
183 WAVEFORMATEXTENSIBLE *pwfxe;
188 pwfxe = (WAVEFORMATEXTENSIBLE *) dsb->pwfx;
190 if ((pwfxe->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) || ((pwfxe->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
191 && (IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))))
194 /* calculate the 10ms write lead */
195 dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
197 if ((dsb->pwfx->wBitsPerSample == dsb->device->pwfx->wBitsPerSample) &&
198 (dsb->pwfx->nChannels == dsb->device->pwfx->nChannels) && !needresample && !ieee)
200 dsb->freqAcc = dsb->freqAccNext = 0;
201 dsb->freqneeded = needresample;
203 dsb->get = ieee ? getbpp[4] : getbpp[dsb->pwfx->wBitsPerSample/8 - 1];
204 dsb->put = putbpp[dsb->device->pwfx->wBitsPerSample/8 - 1];
209 DSOUND_RecalcFreqAcc(dsb);
211 dsb->tmp_buffer_len = dsb->buflen / bAlign * pAlign;
213 else dsb->tmp_buffer_len = dsb->buflen;
214 dsb->buf_mixpos = DSOUND_secpos_to_bufpos(dsb, dsb->sec_mixpos, 0, NULL);
218 * Check for application callback requests for when the play position
219 * reaches certain points.
221 * The offsets that will be triggered will be those between the recorded
222 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
223 * beyond that position.
225 void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
229 LPDSBPOSITIONNOTIFY event;
230 TRACE("(%p,%d)\n",dsb,len);
232 if (dsb->nrofnotifies == 0)
235 TRACE("(%p) buflen = %d, playpos = %d, len = %d\n",
236 dsb, dsb->buflen, playpos, len);
237 for (i = 0; i < dsb->nrofnotifies ; i++) {
238 event = dsb->notifies + i;
239 offset = event->dwOffset;
240 TRACE("checking %d, position %d, event = %p\n",
241 i, offset, event->hEventNotify);
242 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
243 /* OK. [Inside DirectX, p274] */
244 /* Windows does not seem to enforce this, and some apps rely */
245 /* on that, so we can't stop there. */
247 /* This also means we can't sort the entries by offset, */
248 /* because DSBPN_OFFSETSTOP == -1 */
249 if (offset == DSBPN_OFFSETSTOP) {
250 if (dsb->state == STATE_STOPPED) {
251 SetEvent(event->hEventNotify);
252 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
256 if ((playpos + len) >= dsb->buflen) {
257 if ((offset < ((playpos + len) % dsb->buflen)) ||
258 (offset >= playpos)) {
259 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
260 SetEvent(event->hEventNotify);
263 if ((offset >= playpos) && (offset < (playpos + len))) {
264 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
265 SetEvent(event->hEventNotify);
272 * Copy frames from the given input buffer to the given output buffer.
273 * Translate 8 <-> 16 bits and mono <-> stereo
275 static inline void cp_fields(const IDirectSoundBufferImpl *dsb,
276 UINT ostride, UINT count, UINT freqAcc)
278 DWORD ipos = dsb->sec_mixpos;
279 UINT istride = dsb->pwfx->nBlockAlign;
280 UINT adj = dsb->freqAdjust;
281 DirectSoundDevice *device = dsb->device;
286 while (count-- > 0) {
287 if (device->pwfx->nChannels == dsb->pwfx->nChannels ||
288 (device->pwfx->nChannels == 2 && dsb->pwfx->nChannels == 6) ||
289 (device->pwfx->nChannels == 8 && dsb->pwfx->nChannels == 2) ||
290 (device->pwfx->nChannels == 6 && dsb->pwfx->nChannels == 2)) {
291 value = dsb->get(dsb, ipos, 0);
292 dsb->put(dsb, opos, 0, value);
293 if (device->pwfx->nChannels == 2 || dsb->pwfx->nChannels == 2) {
294 value = dsb->get(dsb, ipos, 1);
295 dsb->put(dsb, opos, 1, value);
299 if (device->pwfx->nChannels == 1 && dsb->pwfx->nChannels == 2)
301 float val = (dsb->get(dsb, ipos, 0) + dsb->get(dsb, ipos, 1)) / 2.;
303 dsb->put(dsb, opos, 0, val);
306 if (device->pwfx->nChannels == 2 && dsb->pwfx->nChannels == 1)
308 value = dsb->get(dsb, ipos, 0);
309 dsb->put(dsb, opos, 0, value);
310 dsb->put(dsb, opos, 1, value);
314 adv = (freqAcc >> DSOUND_FREQSHIFT);
315 freqAcc &= (1 << DSOUND_FREQSHIFT) - 1;
316 ipos += adv * istride;
322 * Calculate the distance between two buffer offsets, taking wraparound
325 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
327 /* If these asserts fail, the problem is not here, but in the underlying code */
328 assert(ptr1 < buflen);
329 assert(ptr2 < buflen);
333 return buflen + ptr1 - ptr2;
337 * Mix at most the given amount of data into the allocated temporary buffer
338 * of the given secondary buffer, starting from the dsb's first currently
339 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
340 * and bits-per-sample so that it is ideal for the primary buffer.
341 * Doesn't perform any mixing - this is a straight copy/convert operation.
343 * dsb = the secondary buffer
344 * writepos = Starting position of changed buffer
345 * len = number of bytes to resample from writepos
347 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
349 static void DSOUND_MixToTemporary(const IDirectSoundBufferImpl *dsb, DWORD tmp_len)
351 INT oAdvance = dsb->device->pwfx->nBlockAlign;
352 INT size = tmp_len / oAdvance;
355 if (dsb->device->tmp_buffer_len < tmp_len || !dsb->device->tmp_buffer)
357 dsb->device->tmp_buffer_len = tmp_len;
358 if (dsb->device->tmp_buffer)
359 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, tmp_len);
361 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, tmp_len);
364 /* Check for same sample rate */
365 if (dsb->freq == dsb->device->pwfx->nSamplesPerSec) {
366 TRACE("(%p) Same sample rate %d = primary %d\n", dsb,
367 dsb->freq, dsb->device->pwfx->nSamplesPerSec);
369 cp_fields(dsb, oAdvance, size, 0);
373 /* Mix in different sample rates */
374 TRACE("(%p) Adjusting frequency: %d -> %d\n", dsb, dsb->freq, dsb->device->pwfx->nSamplesPerSec);
376 DSOUND_secpos_to_bufpos(dsb, dsb->sec_mixpos, dsb->sec_mixpos, &freqAcc);
378 /* FIXME: Small problem here when we're overwriting buf_mixpos, it then STILL uses old freqAcc, not sure if it matters or not */
379 cp_fields(dsb, oAdvance, size, freqAcc);
382 /** Apply volume to the given soundbuffer from (primary) position writepos and length len
383 * Returns: NULL if no volume needs to be applied
384 * or else a memory handle that holds 'len' volume adjusted buffer */
385 static LPBYTE DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT len)
391 INT nChannels = dsb->device->pwfx->nChannels;
392 LPBYTE mem = dsb->device->tmp_buffer;
394 TRACE("(%p,%d)\n",dsb,len);
395 TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalLeftAmpFactor,
396 dsb->volpan.dwTotalRightAmpFactor);
398 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
399 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
400 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
401 return NULL; /* Nothing to do */
403 if (nChannels != 1 && nChannels != 2)
405 FIXME("There is no support for %d channels\n", nChannels);
409 if (dsb->device->pwfx->wBitsPerSample != 8 && dsb->device->pwfx->wBitsPerSample != 16)
411 FIXME("There is no support for %d bpp\n", dsb->device->pwfx->wBitsPerSample);
415 assert(dsb->device->tmp_buffer_len >= len && dsb->device->tmp_buffer);
417 bpc = dsb->device->tmp_buffer;
420 vLeft = dsb->volpan.dwTotalLeftAmpFactor;
422 vRight = dsb->volpan.dwTotalRightAmpFactor;
426 switch (dsb->device->pwfx->wBitsPerSample) {
428 /* 8-bit WAV is unsigned, but we need to operate */
429 /* on signed data for this to work properly */
430 for (i = 0; i < len-1; i+=2) {
431 *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
432 *(bpc++) = (((*(mem++) - 128) * vRight) >> 16) + 128;
434 if (len % 2 == 1 && nChannels == 1)
435 *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
438 /* 16-bit WAV is signed -- much better */
439 for (i = 0; i < len-3; i += 4) {
440 *(bps++) = (*(mems++) * vLeft) >> 16;
441 *(bps++) = (*(mems++) * vRight) >> 16;
443 if (len % 4 == 2 && nChannels == 1)
444 *(bps++) = ((INT)*(mems++) * vLeft) >> 16;
447 return dsb->device->tmp_buffer;
451 * Mix (at most) the given number of bytes into the given position of the
452 * device buffer, from the secondary buffer "dsb" (starting at the current
453 * mix position for that buffer).
455 * Returns the number of bytes actually mixed into the device buffer. This
456 * will match fraglen unless the end of the secondary buffer is reached
457 * (and it is not looping).
459 * dsb = the secondary buffer to mix from
460 * writepos = position (offset) in device buffer to write at
461 * fraglen = number of bytes to mix
463 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
465 INT len = fraglen, ilen;
467 DWORD oldpos, mixbufpos;
469 TRACE("buf_mixpos=%d/%d sec_mixpos=%d/%d\n", dsb->buf_mixpos, dsb->tmp_buffer_len, dsb->sec_mixpos, dsb->buflen);
470 TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
472 assert(dsb->buf_mixpos + len <= dsb->tmp_buffer_len);
474 if (len % dsb->device->pwfx->nBlockAlign) {
475 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
476 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
477 len -= len % nBlockAlign; /* data alignment */
480 /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
481 DSOUND_MixToTemporary(dsb, len);
482 ibuf = dsb->device->tmp_buffer;
484 /* Apply volume if needed */
485 volbuf = DSOUND_MixerVol(dsb, len);
489 mixbufpos = DSOUND_bufpos_to_mixpos(dsb->device, writepos);
490 /* Now mix the temporary buffer into the devices main buffer */
491 if ((writepos + len) <= dsb->device->buflen)
492 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, len);
495 DWORD todo = dsb->device->buflen - writepos;
496 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, todo);
497 dsb->device->mixfunction(ibuf + todo, dsb->device->mix_buffer, len - todo);
500 oldpos = dsb->sec_mixpos;
501 dsb->buf_mixpos += len;
503 if (dsb->buf_mixpos >= dsb->tmp_buffer_len) {
504 if (dsb->playflags & DSBPLAY_LOOPING) {
505 dsb->buf_mixpos -= dsb->tmp_buffer_len;
507 dsb->buf_mixpos = dsb->sec_mixpos = 0;
508 dsb->state = STATE_STOPPED;
510 DSOUND_RecalcFreqAcc(dsb);
513 dsb->sec_mixpos = DSOUND_bufpos_to_secpos(dsb, dsb->buf_mixpos);
514 ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
515 /* check for notification positions */
516 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
517 dsb->state != STATE_STARTING) {
518 DSOUND_CheckEvent(dsb, oldpos, ilen);
521 /* increase mix position */
522 dsb->primary_mixpos += len;
523 if (dsb->primary_mixpos >= dsb->device->buflen)
524 dsb->primary_mixpos -= dsb->device->buflen;
529 * Mix some frames from the given secondary buffer "dsb" into the device
532 * dsb = the secondary buffer
533 * playpos = the current play position in the device buffer (primary buffer)
534 * writepos = the current safe-to-write position in the device buffer
535 * mixlen = the maximum number of bytes in the primary buffer to mix, from the
538 * Returns: the number of bytes beyond the writepos that were mixed.
540 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD mixlen)
542 /* The buffer's primary_mixpos may be before or after the device
543 * buffer's mixpos, but both must be ahead of writepos. */
546 TRACE("(%p,%d,%d)\n",dsb,writepos,mixlen);
547 TRACE("writepos=%d, buf_mixpos=%d, primary_mixpos=%d, mixlen=%d\n", writepos, dsb->buf_mixpos, dsb->primary_mixpos, mixlen);
548 TRACE("looping=%d, leadin=%d, buflen=%d\n", dsb->playflags, dsb->leadin, dsb->tmp_buffer_len);
550 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
551 if (dsb->leadin && dsb->state == STATE_STARTING)
553 if (mixlen > 2 * dsb->device->fraglen)
555 dsb->primary_mixpos += mixlen - 2 * dsb->device->fraglen;
556 dsb->primary_mixpos %= dsb->device->buflen;
561 /* calculate how much pre-buffering has already been done for this buffer */
562 primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
565 if(mixlen < primary_done)
567 /* Should *NEVER* happen */
568 ERR("Fatal error. Under/Overflow? primary_done=%d, mixpos=%d/%d (%d/%d), primary_mixpos=%d, writepos=%d, mixlen=%d\n", primary_done,dsb->buf_mixpos,dsb->tmp_buffer_len,dsb->sec_mixpos, dsb->buflen, dsb->primary_mixpos, writepos, mixlen);
569 dsb->primary_mixpos = writepos + mixlen;
570 dsb->primary_mixpos %= dsb->device->buflen;
574 /* take into account already mixed data */
575 mixlen -= primary_done;
577 TRACE("primary_done=%d, mixlen (primary) = %i\n", primary_done, mixlen);
582 /* First try to mix to the end of the buffer if possible
583 * Theoretically it would allow for better optimization
585 if (mixlen + dsb->buf_mixpos >= dsb->tmp_buffer_len)
587 DWORD newmixed, mixfirst = dsb->tmp_buffer_len - dsb->buf_mixpos;
588 newmixed = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixfirst);
591 if (dsb->playflags & DSBPLAY_LOOPING)
592 while (newmixed && mixlen)
594 mixfirst = (dsb->tmp_buffer_len < mixlen ? dsb->tmp_buffer_len : mixlen);
595 newmixed = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixfirst);
599 else DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixlen);
601 /* re-calculate the primary done */
602 primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
604 TRACE("new primary_mixpos=%d, total mixed data=%d\n", dsb->primary_mixpos, primary_done);
606 /* Report back the total prebuffered amount for this buffer */
611 * For a DirectSoundDevice, go through all the currently playing buffers and
612 * mix them in to the device buffer.
614 * writepos = the current safe-to-write position in the primary buffer
615 * mixlen = the maximum amount to mix into the primary buffer
616 * (beyond the current writepos)
617 * recover = true if the sound device may have been reset and the write
618 * position in the device buffer changed
619 * all_stopped = reports back if all buffers have stopped
621 * Returns: the length beyond the writepos that was mixed to.
624 static DWORD DSOUND_MixToPrimary(const DirectSoundDevice *device, DWORD writepos, DWORD mixlen, BOOL recover, BOOL *all_stopped)
628 IDirectSoundBufferImpl *dsb;
630 /* unless we find a running buffer, all have stopped */
633 TRACE("(%d,%d,%d)\n", writepos, mixlen, recover);
634 for (i = 0; i < device->nrofbuffers; i++) {
635 dsb = device->buffers[i];
637 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
639 if (dsb->buflen && dsb->state) {
640 TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
641 RtlAcquireResourceShared(&dsb->lock, TRUE);
642 /* if buffer is stopping it is stopped now */
643 if (dsb->state == STATE_STOPPING) {
644 dsb->state = STATE_STOPPED;
645 DSOUND_CheckEvent(dsb, 0, 0);
646 } else if (dsb->state != STATE_STOPPED) {
648 /* if recovering, reset the mix position */
649 if ((dsb->state == STATE_STARTING) || recover) {
650 dsb->primary_mixpos = writepos;
653 /* if the buffer was starting, it must be playing now */
654 if (dsb->state == STATE_STARTING)
655 dsb->state = STATE_PLAYING;
657 /* mix next buffer into the main buffer */
658 len = DSOUND_MixOne(dsb, writepos, mixlen);
660 if (!minlen) minlen = len;
662 /* record the minimum length mixed from all buffers */
663 /* we only want to return the length which *all* buffers have mixed */
664 else if (len) minlen = (len < minlen) ? len : minlen;
666 *all_stopped = FALSE;
668 RtlReleaseResource(&dsb->lock);
672 TRACE("Mixed at least %d from all buffers\n", minlen);
677 * Add buffers to the emulated wave device system.
679 * device = The current dsound playback device
680 * force = If TRUE, the function will buffer up as many frags as possible,
681 * even though and will ignore the actual state of the primary buffer.
686 static void DSOUND_WaveQueue(DirectSoundDevice *device, BOOL force)
688 DWORD prebuf_frames, buf_offs_bytes, wave_fragpos;
693 TRACE("(%p)\n", device);
695 /* calculate the current wave frag position */
696 wave_fragpos = (device->pwplay + device->pwqueue) % device->helfrags;
698 /* calculate the current wave write position */
699 buf_offs_bytes = wave_fragpos * device->fraglen;
701 TRACE("wave_fragpos = %i, buf_offs_bytes = %i, pwqueue = %i, prebuf = %i\n",
702 wave_fragpos, buf_offs_bytes, device->pwqueue, device->prebuf);
706 /* check remaining prebuffered frags */
707 prebuf_frags = device->mixpos / device->fraglen;
708 if (prebuf_frags == device->helfrags)
710 TRACE("wave_fragpos = %d, mixpos_frags = %d\n", wave_fragpos, prebuf_frags);
711 if (prebuf_frags < wave_fragpos)
712 prebuf_frags += device->helfrags;
713 prebuf_frags -= wave_fragpos;
714 TRACE("wanted prebuf_frags = %d\n", prebuf_frags);
717 /* buffer the maximum amount of frags */
718 prebuf_frags = device->prebuf;
720 /* limit to the queue we have left */
721 if ((prebuf_frags + device->pwqueue) > device->prebuf)
722 prebuf_frags = device->prebuf - device->pwqueue;
724 TRACE("prebuf_frags = %i\n", prebuf_frags);
730 device->pwqueue += prebuf_frags;
732 prebuf_frames = ((prebuf_frags + wave_fragpos > device->helfrags) ?
733 (device->helfrags - wave_fragpos) :
734 (prebuf_frags)) * device->fraglen / device->pwfx->nBlockAlign;
736 hr = IAudioRenderClient_GetBuffer(device->render, prebuf_frames, &buffer);
738 WARN("GetBuffer failed: %08x\n", hr);
742 memcpy(buffer, device->buffer + buf_offs_bytes,
743 prebuf_frames * device->pwfx->nBlockAlign);
745 hr = IAudioRenderClient_ReleaseBuffer(device->render, prebuf_frames, 0);
747 WARN("ReleaseBuffer failed: %08x\n", hr);
751 /* check if anything wrapped */
752 prebuf_frags = prebuf_frags + wave_fragpos - device->helfrags;
753 if(prebuf_frags > 0){
754 prebuf_frames = prebuf_frags * device->fraglen / device->pwfx->nBlockAlign;
756 hr = IAudioRenderClient_GetBuffer(device->render, prebuf_frames, &buffer);
758 WARN("GetBuffer failed: %08x\n", hr);
762 memcpy(buffer, device->buffer, prebuf_frames * device->pwfx->nBlockAlign);
764 hr = IAudioRenderClient_ReleaseBuffer(device->render, prebuf_frames, 0);
766 WARN("ReleaseBuffer failed: %08x\n", hr);
771 TRACE("queue now = %i\n", device->pwqueue);
775 * Perform mixing for a Direct Sound device. That is, go through all the
776 * secondary buffers (the sound bites currently playing) and mix them in
777 * to the primary buffer (the device buffer).
779 static void DSOUND_PerformMix(DirectSoundDevice *device)
781 UINT64 clock_pos, clock_freq, pos_bytes;
785 TRACE("(%p)\n", device);
788 EnterCriticalSection(&device->mixlock);
790 hr = IAudioClock_GetFrequency(device->clock, &clock_freq);
792 WARN("GetFrequency failed: %08x\n", hr);
793 LeaveCriticalSection(&device->mixlock);
797 hr = IAudioClock_GetPosition(device->clock, &clock_pos, NULL);
799 WARN("GetCurrentPadding failed: %08x\n", hr);
800 LeaveCriticalSection(&device->mixlock);
804 pos_bytes = (clock_pos * device->pwfx->nSamplesPerSec * device->pwfx->nBlockAlign) / clock_freq;
806 delta_frags = (pos_bytes - device->last_pos_bytes) / device->fraglen;
808 device->pwplay += delta_frags;
809 device->pwplay %= device->helfrags;
810 device->pwqueue -= delta_frags;
811 device->last_pos_bytes = pos_bytes - (pos_bytes % device->fraglen);
814 if (device->priolevel != DSSCL_WRITEPRIMARY) {
815 BOOL recover = FALSE, all_stopped = FALSE;
816 DWORD playpos, writepos, writelead, maxq, frag, prebuff_max, prebuff_left, size1, size2, mixplaypos, mixplaypos2;
820 /* the sound of silence */
821 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
823 /* get the position in the primary buffer */
824 if (DSOUND_PrimaryGetPosition(device, &playpos, &writepos) != 0){
825 LeaveCriticalSection(&(device->mixlock));
829 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
830 playpos,writepos,device->playpos,device->mixpos,device->buflen);
831 assert(device->playpos < device->buflen);
833 mixplaypos = DSOUND_bufpos_to_mixpos(device, device->playpos);
834 mixplaypos2 = DSOUND_bufpos_to_mixpos(device, playpos);
836 /* calc maximum prebuff */
837 prebuff_max = (device->prebuf * device->fraglen);
838 if (playpos + prebuff_max >= device->helfrags * device->fraglen)
839 prebuff_max += device->buflen - device->helfrags * device->fraglen;
841 /* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
842 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
843 writelead = DSOUND_BufPtrDiff(device->buflen, writepos, playpos);
845 /* check for underrun. underrun occurs when the write position passes the mix position
846 * also wipe out just-played sound data */
847 if((prebuff_left > prebuff_max) || (device->state == STATE_STOPPED) || (device->state == STATE_STARTING)){
848 if (device->state == STATE_STOPPING || device->state == STATE_PLAYING)
849 WARN("Probable buffer underrun\n");
850 else TRACE("Buffer starting or buffer underrun\n");
852 /* recover mixing for all buffers */
855 /* reset mix position to write position */
856 device->mixpos = writepos;
858 ZeroMemory(device->mix_buffer, device->mix_buffer_len);
859 ZeroMemory(device->buffer, device->buflen);
860 } else if (playpos < device->playpos) {
861 buf1 = device->buffer + device->playpos;
862 buf2 = device->buffer;
863 size1 = device->buflen - device->playpos;
865 FillMemory(device->mix_buffer + mixplaypos, device->mix_buffer_len - mixplaypos, 0);
866 FillMemory(device->mix_buffer, mixplaypos2, 0);
867 FillMemory(buf1, size1, nfiller);
868 if (playpos && (!buf2 || !size2))
869 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__, device->playpos, device->mixpos, playpos, writepos);
870 FillMemory(buf2, size2, nfiller);
872 buf1 = device->buffer + device->playpos;
874 size1 = playpos - device->playpos;
876 FillMemory(device->mix_buffer + mixplaypos, mixplaypos2 - mixplaypos, 0);
877 FillMemory(buf1, size1, nfiller);
879 device->playpos = playpos;
881 /* find the maximum we can prebuffer from current write position */
882 maxq = (writelead < prebuff_max) ? (prebuff_max - writelead) : 0;
884 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
885 prebuff_left, device->prebuf, device->fraglen, prebuff_max, writelead);
888 frag = DSOUND_MixToPrimary(device, writepos, maxq, recover, &all_stopped);
890 if (frag + writepos > device->buflen)
892 DWORD todo = device->buflen - writepos;
893 device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, todo);
894 device->normfunction(device->mix_buffer, device->buffer, frag - todo);
897 device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, frag);
899 /* update the mix position, taking wrap-around into account */
900 device->mixpos = writepos + frag;
901 device->mixpos %= device->buflen;
903 /* update prebuff left */
904 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
906 /* check if have a whole fragment */
907 if (prebuff_left >= device->fraglen){
909 /* update the wave queue */
910 DSOUND_WaveQueue(device, FALSE);
912 /* buffers are full. start playing if applicable */
913 if(device->state == STATE_STARTING){
914 TRACE("started primary buffer\n");
915 if(DSOUND_PrimaryPlay(device) != DS_OK){
916 WARN("DSOUND_PrimaryPlay failed\n");
919 /* we are playing now */
920 device->state = STATE_PLAYING;
924 /* buffers are full. start stopping if applicable */
925 if(device->state == STATE_STOPPED){
926 TRACE("restarting primary buffer\n");
927 if(DSOUND_PrimaryPlay(device) != DS_OK){
928 WARN("DSOUND_PrimaryPlay failed\n");
931 /* start stopping again. as soon as there is no more data, it will stop */
932 device->state = STATE_STOPPING;
937 /* if device was stopping, its for sure stopped when all buffers have stopped */
938 else if((all_stopped == TRUE) && (device->state == STATE_STOPPING)){
939 TRACE("All buffers have stopped. Stopping primary buffer\n");
940 device->state = STATE_STOPPED;
942 /* stop the primary buffer now */
943 DSOUND_PrimaryStop(device);
948 DSOUND_WaveQueue(device, TRUE);
950 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
951 if (device->state == STATE_STARTING) {
952 if (DSOUND_PrimaryPlay(device) != DS_OK)
953 WARN("DSOUND_PrimaryPlay failed\n");
955 device->state = STATE_PLAYING;
957 else if (device->state == STATE_STOPPING) {
958 if (DSOUND_PrimaryStop(device) != DS_OK)
959 WARN("DSOUND_PrimaryStop failed\n");
961 device->state = STATE_STOPPED;
965 LeaveCriticalSection(&(device->mixlock));
969 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD_PTR dwUser,
970 DWORD_PTR dw1, DWORD_PTR dw2)
972 DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
973 DWORD start_time = GetTickCount();
975 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
976 TRACE("entering at %d\n", start_time);
978 RtlAcquireResourceShared(&(device->buffer_list_lock), TRUE);
981 DSOUND_PerformMix(device);
983 RtlReleaseResource(&(device->buffer_list_lock));
985 end_time = GetTickCount();
986 TRACE("completed processing at %d, duration = %d\n", end_time, end_time - start_time);