3 * Copyright 1998 Marcus Meissner
4 * Copyright 1998 Rob Riggs
5 * Copyright 2000-2002 TransGaming Technologies, Inc.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include <sys/types.h>
26 #include <sys/fcntl.h>
32 #include <math.h> /* Insomnia - pow() function */
42 #include "wine/windef16.h"
43 #include "wine/debug.h"
46 #include "dsound_private.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
50 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
54 /* the AmpFactors are expressed in 16.16 fixed point */
55 volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 65536);
56 /* FIXME: dwPan{Left|Right}AmpFactor */
58 /* FIXME: use calculated vol and pan ampfactors */
59 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
60 volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 65536);
61 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
62 volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 65536);
64 TRACE("left = %lx, right = %lx\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
67 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
71 sw = dsb->wfx.nChannels * (dsb->wfx.wBitsPerSample / 8);
72 /* calculate the 10ms write lead */
73 dsb->writelead = (dsb->freq / 100) * sw;
76 void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len)
80 LPDSBPOSITIONNOTIFY event;
82 if (dsb->nrofnotifies == 0)
85 TRACE("(%p) buflen = %ld, playpos = %ld, len = %d\n",
86 dsb, dsb->buflen, dsb->playpos, len);
87 for (i = 0; i < dsb->nrofnotifies ; i++) {
88 event = dsb->notifies + i;
89 offset = event->dwOffset;
90 TRACE("checking %d, position %ld, event = %p\n",
91 i, offset, event->hEventNotify);
92 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
93 /* OK. [Inside DirectX, p274] */
95 /* This also means we can't sort the entries by offset, */
96 /* because DSBPN_OFFSETSTOP == -1 */
97 if (offset == DSBPN_OFFSETSTOP) {
98 if (dsb->state == STATE_STOPPED) {
99 SetEvent(event->hEventNotify);
100 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
105 if ((dsb->playpos + len) >= dsb->buflen) {
106 if ((offset < ((dsb->playpos + len) % dsb->buflen)) ||
107 (offset >= dsb->playpos)) {
108 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
109 SetEvent(event->hEventNotify);
112 if ((offset >= dsb->playpos) && (offset < (dsb->playpos + len))) {
113 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
114 SetEvent(event->hEventNotify);
120 /* WAV format info can be found at: */
122 /* http://www.cwi.nl/ftp/audio/AudioFormats.part2 */
123 /* ftp://ftp.cwi.nl/pub/audio/RIFF-format */
125 /* Import points to remember: */
127 /* 8-bit WAV is unsigned */
128 /* 16-bit WAV is signed */
130 static inline INT16 cvtU8toS16(BYTE byte)
132 INT16 s = (byte - 128) << 8;
137 static inline BYTE cvtS16toU8(INT16 word)
139 BYTE b = (word + 32768) >> 8;
144 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, BYTE *ibuf, BYTE *obuf )
147 if (dsb->wfx.nChannels == 2) {
148 if (dsb->wfx.wBitsPerSample == 8) {
149 /* avoid needless 8->16->8 conversion */
150 if ( (dsound->wfx.wBitsPerSample == 8) && (dsound->wfx.nChannels == 2) ) {
155 fl = cvtU8toS16(*ibuf);
156 fr = cvtU8toS16(*(ibuf + 1));
157 } else if (dsb->wfx.wBitsPerSample == 16) {
158 fl = *((INT16 *)ibuf);
159 fr = *(((INT16 *)ibuf) + 1);
161 } else if (dsb->wfx.nChannels == 1) {
162 if (dsb->wfx.wBitsPerSample == 8) {
163 /* avoid needless 8->16->8 conversion */
164 if ( (dsound->wfx.wBitsPerSample == 8) && (dsound->wfx.nChannels == 1) ) {
168 fl = cvtU8toS16(*ibuf);
170 } else if (dsb->wfx.wBitsPerSample == 16) {
171 fl = *((INT16 *)ibuf);
175 if (dsound->wfx.nChannels == 2) {
176 if (dsound->wfx.wBitsPerSample == 8) {
177 *obuf = cvtS16toU8(fl);
178 *(obuf + 1) = cvtS16toU8(fr);
181 if (dsound->wfx.wBitsPerSample == 16) {
182 *((INT16 *)obuf) = fl;
183 *(((INT16 *)obuf) + 1) = fr;
187 if (dsound->wfx.nChannels == 1) {
189 if (dsound->wfx.wBitsPerSample == 8) {
190 *obuf = cvtS16toU8(fl);
193 if (dsound->wfx.wBitsPerSample == 16) {
194 *((INT16 *)obuf) = fl;
200 /* Now with PerfectPitch (tm) technology */
201 static INT DSOUND_MixerNorm(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
203 INT i, size, ipos, ilen;
205 INT iAdvance = dsb->wfx.nBlockAlign;
206 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
208 ibp = dsb->buffer + dsb->buf_mixpos;
211 TRACE("(%p, %p, %p), buf_mixpos=%ld\n", dsb, ibp, obp, dsb->buf_mixpos);
212 /* Check for the best case */
213 if ((dsb->freq == dsb->dsound->wfx.nSamplesPerSec) &&
214 (dsb->wfx.wBitsPerSample == dsb->dsound->wfx.wBitsPerSample) &&
215 (dsb->wfx.nChannels == dsb->dsound->wfx.nChannels)) {
216 DWORD bytesleft = dsb->buflen - dsb->buf_mixpos;
217 TRACE("(%p) Best case\n", dsb);
218 if (len <= bytesleft )
219 memcpy(obp, ibp, len);
221 memcpy(obp, ibp, bytesleft );
222 memcpy(obp + bytesleft, dsb->buffer, len - bytesleft);
227 /* Check for same sample rate */
228 if (dsb->freq == dsb->dsound->wfx.nSamplesPerSec) {
229 TRACE("(%p) Same sample rate %ld = primary %ld\n", dsb,
230 dsb->freq, dsb->dsound->wfx.nSamplesPerSec);
232 for (i = 0; i < len; i += oAdvance) {
233 cp_fields(dsb, ibp, obp );
237 if (ibp >= (BYTE *)(dsb->buffer + dsb->buflen))
238 ibp = dsb->buffer; /* wrap */
243 /* Mix in different sample rates */
245 /* New PerfectPitch(tm) Technology (c) 1998 Rob Riggs */
246 /* Patent Pending :-] */
248 /* Patent enhancements (c) 2000 Ove KÃ¥ven,
249 * TransGaming Technologies Inc. */
251 /* FIXME("(%p) Adjusting frequency: %ld -> %ld (need optimization)\n",
252 dsb, dsb->freq, dsb->dsound->wfx.nSamplesPerSec); */
254 size = len / oAdvance;
256 ipos = dsb->buf_mixpos;
257 for (i = 0; i < size; i++) {
258 cp_fields(dsb, (dsb->buffer + ipos), obp);
260 dsb->freqAcc += dsb->freqAdjust;
261 if (dsb->freqAcc >= (1<<DSOUND_FREQSHIFT)) {
262 ULONG adv = (dsb->freqAcc>>DSOUND_FREQSHIFT) * iAdvance;
263 dsb->freqAcc &= (1<<DSOUND_FREQSHIFT)-1;
264 ipos += adv; ilen += adv;
265 while (ipos >= dsb->buflen)
272 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
274 INT i, inc = dsb->dsound->wfx.wBitsPerSample >> 3;
276 INT16 *bps = (INT16 *) buf;
278 TRACE("(%p) left = %lx, right = %lx\n", dsb,
279 dsb->cvolpan.dwTotalLeftAmpFactor, dsb->cvolpan.dwTotalRightAmpFactor);
280 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->cvolpan.lPan == 0)) &&
281 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->cvolpan.lVolume == 0)) &&
282 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
283 return; /* Nothing to do */
285 /* If we end up with some bozo coder using panning or 3D sound */
286 /* with a mono primary buffer, it could sound very weird using */
287 /* this method. Oh well, tough patooties. */
289 for (i = 0; i < len; i += inc) {
295 /* 8-bit WAV is unsigned, but we need to operate */
296 /* on signed data for this to work properly */
298 val = ((val * (i & inc ? dsb->cvolpan.dwTotalRightAmpFactor : dsb->cvolpan.dwTotalLeftAmpFactor)) >> 16);
303 /* 16-bit WAV is signed -- much better */
305 val = ((val * ((i & inc) ? dsb->cvolpan.dwTotalRightAmpFactor : dsb->cvolpan.dwTotalLeftAmpFactor)) >> 16);
311 FIXME("MixerVol had a nasty error\n");
316 static void *tmp_buffer;
317 static size_t tmp_buffer_len = 0;
319 static void *DSOUND_tmpbuffer(size_t len)
321 if (len>tmp_buffer_len) {
322 void *new_buffer = realloc(tmp_buffer, len);
324 tmp_buffer = new_buffer;
325 tmp_buffer_len = len;
332 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
334 INT i, len, ilen, temp, field;
335 INT advance = dsb->dsound->wfx.wBitsPerSample >> 3;
336 BYTE *buf, *ibuf, *obuf;
337 INT16 *ibufs, *obufs;
340 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
341 temp = MulDiv(dsb->dsound->wfx.nAvgBytesPerSec, dsb->buflen,
342 dsb->nAvgBytesPerSec) -
343 MulDiv(dsb->dsound->wfx.nAvgBytesPerSec, dsb->buf_mixpos,
344 dsb->nAvgBytesPerSec);
345 len = (len > temp) ? temp : len;
347 len &= ~3; /* 4 byte alignment */
350 /* This should only happen if we aren't looping and temp < 4 */
352 /* We skip the remainder, so check for possible events */
353 DSOUND_CheckEvent(dsb, dsb->buflen - dsb->buf_mixpos);
355 dsb->state = STATE_STOPPED;
357 dsb->last_playpos = 0;
360 /* Check for DSBPN_OFFSETSTOP */
361 DSOUND_CheckEvent(dsb, 0);
365 /* Been seeing segfaults in malloc() for some reason... */
366 TRACE("allocating buffer (size = %d)\n", len);
367 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
370 TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
372 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
373 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
374 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
375 DSOUND_MixerVol(dsb, ibuf, len);
377 obuf = dsb->dsound->buffer + writepos;
378 for (i = 0; i < len; i += advance) {
379 obufs = (INT16 *) obuf;
380 ibufs = (INT16 *) ibuf;
381 if (dsb->dsound->wfx.wBitsPerSample == 8) {
382 /* 8-bit WAV is unsigned */
383 field = (*ibuf - 128);
384 field += (*obuf - 128);
385 field = field > 127 ? 127 : field;
386 field = field < -128 ? -128 : field;
389 /* 16-bit WAV is signed */
392 field = field > 32767 ? 32767 : field;
393 field = field < -32768 ? -32768 : field;
398 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
399 obuf = dsb->dsound->buffer;
403 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY)
404 DSOUND_CheckEvent(dsb, ilen);
406 if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
407 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
408 * not the MIX position... but if the sound buffer is bigger than our prebuffering
409 * (which must be the case for the streaming buffers that need this hack anyway)
410 * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
414 dsb->buf_mixpos += ilen;
416 if (dsb->buf_mixpos >= dsb->buflen) {
417 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
418 dsb->state = STATE_STOPPED;
420 dsb->last_playpos = 0;
423 DSOUND_CheckEvent(dsb, 0); /* For DSBPN_OFFSETSTOP */
426 while (dsb->buf_mixpos >= dsb->buflen)
427 dsb->buf_mixpos -= dsb->buflen;
428 if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
429 dsb->leadin = FALSE; /* HACK: see above */
436 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
439 INT advance = dsb->dsound->wfx.wBitsPerSample >> 3;
440 BYTE *buf, *ibuf, *obuf;
441 INT16 *ibufs, *obufs;
443 len &= ~3; /* 4 byte alignment */
445 TRACE("allocating buffer (size = %ld)\n", len);
446 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
449 TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
451 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
452 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
453 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
454 DSOUND_MixerVol(dsb, ibuf, len);
456 /* subtract instead of add, to phase out premixed data */
457 obuf = dsb->dsound->buffer + writepos;
458 for (i = 0; i < len; i += advance) {
459 obufs = (INT16 *) obuf;
460 ibufs = (INT16 *) ibuf;
461 if (dsb->dsound->wfx.wBitsPerSample == 8) {
462 /* 8-bit WAV is unsigned */
463 field = (*ibuf - 128);
464 field -= (*obuf - 128);
465 field = field > 127 ? 127 : field;
466 field = field < -128 ? -128 : field;
469 /* 16-bit WAV is signed */
472 field = field > 32767 ? 32767 : field;
473 field = field < -32768 ? -32768 : field;
478 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
479 obuf = dsb->dsound->buffer;
484 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
486 DWORD size, flen, len, npos, nlen;
487 INT iAdvance = dsb->wfx.nBlockAlign;
488 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
489 /* determine amount of premixed data to cancel */
491 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
492 dsb->primary_mixpos - writepos;
494 TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
496 /* backtrack the mix position */
497 size = primary_done / oAdvance;
498 flen = size * dsb->freqAdjust;
499 len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
500 flen &= (1<<DSOUND_FREQSHIFT)-1;
501 while (dsb->freqAcc < flen) {
503 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
506 npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
507 dsb->buf_mixpos - len;
508 if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
509 /* stop backtracking at startpos */
510 npos = dsb->startpos;
511 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
512 dsb->buf_mixpos - npos;
514 nlen = len / dsb->wfx.nBlockAlign;
515 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
516 nlen *= dsb->dsound->wfx.nBlockAlign;
518 ((dsb->primary_mixpos < nlen) ? dsb->dsound->buflen : 0) +
519 dsb->primary_mixpos - nlen;
522 dsb->freqAcc -= flen;
523 dsb->buf_mixpos = npos;
524 dsb->primary_mixpos = writepos;
526 TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
527 dsb->buf_mixpos, dsb->primary_mixpos, len);
529 if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
532 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
535 DWORD i, size, flen, len, npos, nlen;
536 INT iAdvance = dsb->wfx.nBlockAlign;
537 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
538 /* determine amount of premixed data to cancel */
540 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
541 dsb->buf_mixpos - buf_writepos;
544 WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
545 /* since this is not implemented yet, just cancel *ALL* prebuffering for now
546 * (which is faster anyway when there's only a single secondary buffer) */
547 dsb->dsound->need_remix = TRUE;
550 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
552 EnterCriticalSection(&dsb->lock);
553 if (dsb->state == STATE_PLAYING) {
554 #if 0 /* this may not be quite reliable yet */
555 dsb->need_remix = TRUE;
557 dsb->dsound->need_remix = TRUE;
560 LeaveCriticalSection(&dsb->lock);
563 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
566 /* determine this buffer's write position */
567 DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, dsb->state & dsb->dsound->state, writepos,
568 writepos, dsb->primary_mixpos, dsb->buf_mixpos);
569 /* determine how much already-mixed data exists */
571 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
572 dsb->buf_mixpos - buf_writepos;
574 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
575 dsb->primary_mixpos - writepos;
577 ((dsb->dsound->mixpos < writepos) ? dsb->dsound->buflen : 0) +
578 dsb->dsound->mixpos - writepos;
581 TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
582 TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
583 TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
585 TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
587 /* save write position for non-GETCURRENTPOSITION2... */
588 dsb->playpos = buf_writepos;
590 /* check whether CalcPlayPosition detected a mixing underrun */
591 if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
592 /* it did, but did we have more to play? */
593 if ((dsb->playflags & DSBPLAY_LOOPING) ||
594 (dsb->buf_mixpos < dsb->buflen)) {
595 /* yes, have to recover */
596 ERR("underrun on sound buffer %p\n", dsb);
597 TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
599 dsb->primary_mixpos = writepos;
602 /* determine how far ahead we should mix */
603 if (((dsb->playflags & DSBPLAY_LOOPING) ||
604 (dsb->leadin && (dsb->probably_valid_to != 0))) &&
605 !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
606 /* if this is a streaming buffer, it typically means that
607 * we should defer mixing past probably_valid_to as long
608 * as we can, to avoid unnecessary remixing */
609 /* the heavy-looking calculations shouldn't be that bad,
610 * as any game isn't likely to be have more than 1 or 2
611 * streaming buffers in use at any time anyway... */
612 DWORD probably_valid_left =
613 (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
614 ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
615 dsb->probably_valid_to - buf_writepos;
616 /* check for leadin condition */
617 if ((probably_valid_left == 0) &&
618 (dsb->probably_valid_to == dsb->startpos) &&
620 probably_valid_left = dsb->buflen;
621 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
622 dsb->probably_valid_to, probably_valid_left);
623 /* check whether the app's time is already up */
624 if (probably_valid_left < dsb->writelead) {
625 WARN("probably_valid_to now within writelead, possible streaming underrun\n");
626 /* once we pass the point of no return,
627 * no reason to hold back anymore */
628 dsb->probably_valid_to = (DWORD)-1;
629 /* we just have to go ahead and mix what we have,
630 * there's no telling what the app is thinking anyway */
632 /* adjust for our frequency and our sample size */
633 probably_valid_left = MulDiv(probably_valid_left,
634 1 << DSOUND_FREQSHIFT,
635 dsb->wfx.nBlockAlign * dsb->freqAdjust) *
636 dsb->dsound->wfx.nBlockAlign;
637 /* check whether to clip mix_len */
638 if (probably_valid_left < mixlen) {
639 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
640 mixlen = probably_valid_left;
644 /* cut mixlen with what's already been mixed */
645 if (mixlen < primary_done) {
646 /* huh? and still CalcPlayPosition didn't
647 * detect an underrun? */
648 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
651 len = mixlen - primary_done;
652 TRACE("remaining mixlen=%ld\n", len);
654 if (len < dsb->dsound->fraglen) {
655 /* smaller than a fragment, wait until it gets larger
656 * before we take the mixing overhead */
657 TRACE("mixlen not worth it, deferring mixing\n");
661 /* ok, we know how much to mix, let's go */
662 still_behind = (adv_done > primary_done);
664 slen = dsb->dsound->buflen - dsb->primary_mixpos;
665 if (slen > len) slen = len;
666 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
668 if ((dsb->primary_mixpos < dsb->dsound->mixpos) &&
669 (dsb->primary_mixpos + slen >= dsb->dsound->mixpos))
670 still_behind = FALSE;
672 dsb->primary_mixpos += slen; len -= slen;
673 while (dsb->primary_mixpos >= dsb->dsound->buflen)
674 dsb->primary_mixpos -= dsb->dsound->buflen;
676 if ((dsb->state == STATE_STOPPED) || !slen) break;
678 TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->mixpos);
679 TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
680 /* return how far we think the primary buffer can
681 * advance its underrun detector...*/
682 if (still_behind) return 0;
683 if ((mixlen - len) < primary_done) return 0;
684 slen = ((dsb->primary_mixpos < dsb->dsound->mixpos) ?
685 dsb->dsound->buflen : 0) + dsb->primary_mixpos -
688 /* the primary_done and still_behind checks above should have worked */
689 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
695 static DWORD DSOUND_MixToPrimary(DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
697 INT i, len, maxlen = 0;
698 IDirectSoundBufferImpl *dsb;
700 TRACE("(%ld,%ld,%ld)\n", playpos, writepos, mixlen);
701 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
702 dsb = dsound->buffers[i];
704 if (!dsb || !(ICOM_VTBL(dsb)))
706 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
707 TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
708 EnterCriticalSection(&(dsb->lock));
709 if (dsb->state == STATE_STOPPING) {
710 DSOUND_MixCancel(dsb, writepos, TRUE);
711 dsb->state = STATE_STOPPED;
713 if ((dsb->state == STATE_STARTING) || recover) {
714 dsb->primary_mixpos = writepos;
715 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
716 dsb->need_remix = FALSE;
718 else if (dsb->need_remix) {
719 DSOUND_MixCancel(dsb, writepos, TRUE);
720 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
721 dsb->need_remix = FALSE;
723 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
724 if (dsb->state == STATE_STARTING)
725 dsb->state = STATE_PLAYING;
726 maxlen = (len > maxlen) ? len : maxlen;
728 LeaveCriticalSection(&(dsb->lock));
735 static void DSOUND_MixReset(DWORD writepos)
738 IDirectSoundBufferImpl *dsb;
741 TRACE("(%ld)\n", writepos);
743 /* the sound of silence */
744 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
746 /* reset all buffer mix positions */
747 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
748 dsb = dsound->buffers[i];
750 if (!dsb || !(ICOM_VTBL(dsb)))
752 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
753 TRACE("Resetting %p\n", dsb);
754 EnterCriticalSection(&(dsb->lock));
755 if (dsb->state == STATE_STOPPING) {
756 dsb->state = STATE_STOPPED;
758 else if (dsb->state == STATE_STARTING) {
761 DSOUND_MixCancel(dsb, writepos, FALSE);
762 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
763 dsb->need_remix = FALSE;
765 LeaveCriticalSection(&(dsb->lock));
769 /* wipe out premixed data */
770 if (dsound->mixpos < writepos) {
771 memset(dsound->buffer + writepos, nfiller, dsound->buflen - writepos);
772 memset(dsound->buffer, nfiller, dsound->mixpos);
774 memset(dsound->buffer + writepos, nfiller, dsound->mixpos - writepos);
777 /* reset primary mix position */
778 dsound->mixpos = writepos;
781 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
783 if (dsound->need_remix) {
784 DSOUND_MixReset(writepos);
785 dsound->need_remix = FALSE;
786 /* maximize Half-Life performance */
787 dsound->prebuf = ds_snd_queue_min;
788 dsound->precount = 0;
791 if (dsound->precount >= 4) {
792 if (dsound->prebuf < ds_snd_queue_max)
794 dsound->precount = 0;
797 TRACE("premix adjust: %d\n", dsound->prebuf);
800 void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
802 if (mixq + dsound->pwqueue > ds_hel_queue) mixq = ds_hel_queue - dsound->pwqueue;
803 TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
804 for (; mixq; mixq--) {
805 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
807 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
812 /* #define SYNC_CALLBACK */
814 void DSOUND_PerformMix(void)
820 RtlAcquireResourceShared(&(dsound->lock), TRUE);
822 if (!dsound || !dsound->ref) {
823 /* seems the dsound object is currently being released */
824 RtlReleaseResource(&(dsound->lock));
828 /* the sound of silence */
829 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
831 /* whether the primary is forced to play even without secondary buffers */
832 forced = ((dsound->state == STATE_PLAYING) || (dsound->state == STATE_STARTING));
834 TRACE("entering at %ld\n", GetTickCount());
835 if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
836 BOOL paused = ((dsound->state == STATE_STOPPED) || (dsound->state == STATE_STARTING));
837 /* FIXME: document variables */
838 DWORD playpos, writepos, inq, maxq, frag;
840 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, &writepos);
842 RtlReleaseResource(&(dsound->lock));
845 /* Well, we *could* do Just-In-Time mixing using the writepos,
846 * but that's a little bit ambitious and unnecessary... */
847 /* rather add our safety margin to the writepos, if we're playing */
849 writepos += dsound->writelead;
850 while (writepos >= dsound->buflen)
851 writepos -= dsound->buflen;
852 } else writepos = playpos;
855 playpos = dsound->pwplay * dsound->fraglen;
858 writepos += ds_hel_margin * dsound->fraglen;
859 while (writepos >= dsound->buflen)
860 writepos -= dsound->buflen;
863 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld\n",
864 playpos,writepos,dsound->playpos,dsound->mixpos);
865 /* wipe out just-played sound data */
866 if (playpos < dsound->playpos) {
867 memset(dsound->buffer + dsound->playpos, nfiller, dsound->buflen - dsound->playpos);
868 memset(dsound->buffer, nfiller, playpos);
870 memset(dsound->buffer + dsound->playpos, nfiller, playpos - dsound->playpos);
872 dsound->playpos = playpos;
874 EnterCriticalSection(&(dsound->mixlock));
876 /* reset mixing if necessary */
877 DSOUND_CheckReset(dsound, writepos);
879 /* check how much prebuffering is left */
880 inq = dsound->mixpos;
882 inq += dsound->buflen;
885 /* find the maximum we can prebuffer */
889 maxq += dsound->buflen;
891 } else maxq = dsound->buflen;
893 /* clip maxq to dsound->prebuf */
894 frag = dsound->prebuf * dsound->fraglen;
895 if (maxq > frag) maxq = frag;
897 /* check for consistency */
899 /* the playback position must have passed our last
900 * mixed position, i.e. it's an underrun, or we have
901 * nothing more to play */
902 TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
904 /* stop the playback now, to allow buffers to refill */
905 if (dsound->state == STATE_PLAYING) {
906 dsound->state = STATE_STARTING;
908 else if (dsound->state == STATE_STOPPING) {
909 dsound->state = STATE_STOPPED;
912 /* how can we have an underrun if we aren't playing? */
913 WARN("unexpected primary state (%ld)\n", dsound->state);
916 /* DSOUND_callback may need this lock */
917 LeaveCriticalSection(&(dsound->mixlock));
919 DSOUND_PrimaryStop(dsound);
921 EnterCriticalSection(&(dsound->mixlock));
924 /* the Stop is supposed to reset play position to beginning of buffer */
925 /* unfortunately, OSS is not able to do so, so get current pointer */
926 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, NULL);
928 LeaveCriticalSection(&(dsound->mixlock));
929 RtlReleaseResource(&(dsound->lock));
933 playpos = dsound->pwplay * dsound->fraglen;
936 dsound->playpos = playpos;
937 dsound->mixpos = writepos;
939 maxq = dsound->buflen;
940 if (maxq > frag) maxq = frag;
941 memset(dsound->buffer, nfiller, dsound->buflen);
946 frag = DSOUND_MixToPrimary(playpos, writepos, maxq, paused);
947 if (forced) frag = maxq - inq;
948 dsound->mixpos += frag;
949 while (dsound->mixpos >= dsound->buflen)
950 dsound->mixpos -= dsound->buflen;
953 /* buffers have been filled, restart playback */
954 if (dsound->state == STATE_STARTING) {
955 dsound->state = STATE_PLAYING;
957 else if (dsound->state == STATE_STOPPED) {
958 /* the dsound is supposed to play if there's something to play
959 * even if it is reported as stopped, so don't let this confuse you */
960 dsound->state = STATE_STOPPING;
962 LeaveCriticalSection(&(dsound->mixlock));
964 DSOUND_PrimaryPlay(dsound);
965 TRACE("starting playback\n");
969 LeaveCriticalSection(&(dsound->mixlock));
971 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
972 if (dsound->state == STATE_STARTING) {
973 DSOUND_PrimaryPlay(dsound);
974 dsound->state = STATE_PLAYING;
976 else if (dsound->state == STATE_STOPPING) {
977 DSOUND_PrimaryStop(dsound);
978 dsound->state = STATE_STOPPED;
981 TRACE("completed processing at %ld\n", GetTickCount());
982 RtlReleaseResource(&(dsound->lock));
985 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
988 ERR("dsound died without killing us?\n");
989 timeKillEvent(timerID);
990 timeEndPeriod(DS_TIME_RES);
998 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1000 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1001 TRACE("entering at %ld, msg=%08x\n", GetTickCount(), msg);
1002 if (msg == MM_WOM_DONE) {
1003 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
1004 if (This->pwqueue == (DWORD)-1) {
1005 TRACE("completed due to reset\n");
1008 /* it could be a bad idea to enter critical section here... if there's lock contention,
1009 * the resulting scheduling delays might obstruct the winmm player thread */
1010 #ifdef SYNC_CALLBACK
1011 EnterCriticalSection(&(This->mixlock));
1013 /* retrieve current values */
1014 fraglen = dsound->fraglen;
1015 buflen = dsound->buflen;
1016 pwplay = dsound->pwplay;
1017 playpos = pwplay * fraglen;
1018 mixpos = dsound->mixpos;
1019 /* check remaining mixed data */
1020 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1021 mixq = inq / fraglen;
1022 if ((inq - (mixq * fraglen)) > 0) mixq++;
1023 /* complete the playing buffer */
1024 TRACE("done playing primary pos=%ld\n", playpos);
1026 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1027 /* write new values */
1028 dsound->pwplay = pwplay;
1030 /* queue new buffer if we have data for it */
1031 if (inq>1) DSOUND_WaveQueue(This, inq-1);
1032 #ifdef SYNC_CALLBACK
1033 LeaveCriticalSection(&(This->lock));
1036 TRACE("completed\n");