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:
126 * 8-bit WAV is unsigned
127 * 16-bit WAV is signed
129 /* Use the same formulas as pcmconverter.c */
130 static inline INT16 cvtU8toS16(BYTE b)
132 return (short)((b+(b << 8))-32768);
135 static inline BYTE cvtS16toU8(INT16 s)
137 return (s >> 8) ^ (unsigned char)0x80;
140 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, BYTE *ibuf, BYTE *obuf )
144 if (dsb->wfx.wBitsPerSample == 8) {
145 if (dsound->wfx.wBitsPerSample == 8 &&
146 dsound->wfx.nChannels == dsb->wfx.nChannels) {
147 /* avoid needless 8->16->8 conversion */
149 if (dsb->wfx.nChannels==2)
153 fl = cvtU8toS16(*ibuf);
154 fr = (dsb->wfx.nChannels==2 ? cvtU8toS16(*(ibuf + 1)) : fl);
156 fl = *((INT16 *)ibuf);
157 fr = (dsb->wfx.nChannels==2 ? *(((INT16 *)ibuf) + 1) : fl);
160 if (dsound->wfx.nChannels == 2) {
161 if (dsound->wfx.wBitsPerSample == 8) {
162 *obuf = cvtS16toU8(fl);
163 *(obuf + 1) = cvtS16toU8(fr);
166 if (dsound->wfx.wBitsPerSample == 16) {
167 *((INT16 *)obuf) = fl;
168 *(((INT16 *)obuf) + 1) = fr;
172 if (dsound->wfx.nChannels == 1) {
174 if (dsound->wfx.wBitsPerSample == 8) {
175 *obuf = cvtS16toU8(fl);
178 if (dsound->wfx.wBitsPerSample == 16) {
179 *((INT16 *)obuf) = fl;
185 /* Now with PerfectPitch (tm) technology */
186 static INT DSOUND_MixerNorm(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
188 INT i, size, ipos, ilen;
190 INT iAdvance = dsb->wfx.nBlockAlign;
191 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
193 ibp = dsb->buffer + dsb->buf_mixpos;
196 TRACE("(%p, %p, %p), buf_mixpos=%ld\n", dsb, ibp, obp, dsb->buf_mixpos);
197 /* Check for the best case */
198 if ((dsb->freq == dsb->dsound->wfx.nSamplesPerSec) &&
199 (dsb->wfx.wBitsPerSample == dsb->dsound->wfx.wBitsPerSample) &&
200 (dsb->wfx.nChannels == dsb->dsound->wfx.nChannels)) {
201 DWORD bytesleft = dsb->buflen - dsb->buf_mixpos;
202 TRACE("(%p) Best case\n", dsb);
203 if (len <= bytesleft )
204 memcpy(obp, ibp, len);
206 memcpy(obp, ibp, bytesleft );
207 memcpy(obp + bytesleft, dsb->buffer, len - bytesleft);
212 /* Check for same sample rate */
213 if (dsb->freq == dsb->dsound->wfx.nSamplesPerSec) {
214 TRACE("(%p) Same sample rate %ld = primary %ld\n", dsb,
215 dsb->freq, dsb->dsound->wfx.nSamplesPerSec);
217 for (i = 0; i < len; i += oAdvance) {
218 cp_fields(dsb, ibp, obp );
222 if (ibp >= (BYTE *)(dsb->buffer + dsb->buflen))
223 ibp = dsb->buffer; /* wrap */
228 /* Mix in different sample rates */
230 /* New PerfectPitch(tm) Technology (c) 1998 Rob Riggs */
231 /* Patent Pending :-] */
233 /* Patent enhancements (c) 2000 Ove Kåven,
234 * TransGaming Technologies Inc. */
236 /* FIXME("(%p) Adjusting frequency: %ld -> %ld (need optimization)\n",
237 dsb, dsb->freq, dsb->dsound->wfx.nSamplesPerSec); */
239 size = len / oAdvance;
241 ipos = dsb->buf_mixpos;
242 for (i = 0; i < size; i++) {
243 cp_fields(dsb, (dsb->buffer + ipos), obp);
245 dsb->freqAcc += dsb->freqAdjust;
246 if (dsb->freqAcc >= (1<<DSOUND_FREQSHIFT)) {
247 ULONG adv = (dsb->freqAcc>>DSOUND_FREQSHIFT) * iAdvance;
248 dsb->freqAcc &= (1<<DSOUND_FREQSHIFT)-1;
249 ipos += adv; ilen += adv;
250 while (ipos >= dsb->buflen)
257 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
259 INT i, inc = dsb->dsound->wfx.wBitsPerSample >> 3;
261 INT16 *bps = (INT16 *) buf;
263 TRACE("(%p) left = %lx, right = %lx\n", dsb,
264 dsb->cvolpan.dwTotalLeftAmpFactor, dsb->cvolpan.dwTotalRightAmpFactor);
265 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->cvolpan.lPan == 0)) &&
266 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->cvolpan.lVolume == 0)) &&
267 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
268 return; /* Nothing to do */
270 /* If we end up with some bozo coder using panning or 3D sound */
271 /* with a mono primary buffer, it could sound very weird using */
272 /* this method. Oh well, tough patooties. */
274 for (i = 0; i < len; i += inc) {
280 /* 8-bit WAV is unsigned, but we need to operate */
281 /* on signed data for this to work properly */
283 val = ((val * (i & inc ? dsb->cvolpan.dwTotalRightAmpFactor : dsb->cvolpan.dwTotalLeftAmpFactor)) >> 16);
288 /* 16-bit WAV is signed -- much better */
290 val = ((val * ((i & inc) ? dsb->cvolpan.dwTotalRightAmpFactor : dsb->cvolpan.dwTotalLeftAmpFactor)) >> 16);
296 FIXME("MixerVol had a nasty error\n");
301 static void *tmp_buffer;
302 static size_t tmp_buffer_len = 0;
304 static void *DSOUND_tmpbuffer(size_t len)
306 if (len>tmp_buffer_len) {
307 void *new_buffer = realloc(tmp_buffer, len);
309 tmp_buffer = new_buffer;
310 tmp_buffer_len = len;
317 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
319 INT i, len, ilen, temp, field;
320 INT advance = dsb->dsound->wfx.wBitsPerSample >> 3;
321 BYTE *buf, *ibuf, *obuf;
322 INT16 *ibufs, *obufs;
325 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
326 temp = MulDiv(dsb->dsound->wfx.nAvgBytesPerSec, dsb->buflen,
327 dsb->nAvgBytesPerSec) -
328 MulDiv(dsb->dsound->wfx.nAvgBytesPerSec, dsb->buf_mixpos,
329 dsb->nAvgBytesPerSec);
330 len = (len > temp) ? temp : len;
332 len &= ~3; /* 4 byte alignment */
335 /* This should only happen if we aren't looping and temp < 4 */
337 /* We skip the remainder, so check for possible events */
338 DSOUND_CheckEvent(dsb, dsb->buflen - dsb->buf_mixpos);
340 dsb->state = STATE_STOPPED;
342 dsb->last_playpos = 0;
345 /* Check for DSBPN_OFFSETSTOP */
346 DSOUND_CheckEvent(dsb, 0);
350 /* Been seeing segfaults in malloc() for some reason... */
351 TRACE("allocating buffer (size = %d)\n", len);
352 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
355 TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
357 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
358 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
359 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
360 DSOUND_MixerVol(dsb, ibuf, len);
362 obuf = dsb->dsound->buffer + writepos;
363 for (i = 0; i < len; i += advance) {
364 obufs = (INT16 *) obuf;
365 ibufs = (INT16 *) ibuf;
366 if (dsb->dsound->wfx.wBitsPerSample == 8) {
367 /* 8-bit WAV is unsigned */
368 field = (*ibuf - 128);
369 field += (*obuf - 128);
370 field = field > 127 ? 127 : field;
371 field = field < -128 ? -128 : field;
374 /* 16-bit WAV is signed */
377 field = field > 32767 ? 32767 : field;
378 field = field < -32768 ? -32768 : field;
383 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
384 obuf = dsb->dsound->buffer;
388 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY)
389 DSOUND_CheckEvent(dsb, ilen);
391 if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
392 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
393 * not the MIX position... but if the sound buffer is bigger than our prebuffering
394 * (which must be the case for the streaming buffers that need this hack anyway)
395 * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
399 dsb->buf_mixpos += ilen;
401 if (dsb->buf_mixpos >= dsb->buflen) {
402 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
403 dsb->state = STATE_STOPPED;
405 dsb->last_playpos = 0;
408 DSOUND_CheckEvent(dsb, 0); /* For DSBPN_OFFSETSTOP */
411 while (dsb->buf_mixpos >= dsb->buflen)
412 dsb->buf_mixpos -= dsb->buflen;
413 if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
414 dsb->leadin = FALSE; /* HACK: see above */
421 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
424 INT advance = dsb->dsound->wfx.wBitsPerSample >> 3;
425 BYTE *buf, *ibuf, *obuf;
426 INT16 *ibufs, *obufs;
428 len &= ~3; /* 4 byte alignment */
430 TRACE("allocating buffer (size = %ld)\n", len);
431 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
434 TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
436 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
437 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
438 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
439 DSOUND_MixerVol(dsb, ibuf, len);
441 /* subtract instead of add, to phase out premixed data */
442 obuf = dsb->dsound->buffer + writepos;
443 for (i = 0; i < len; i += advance) {
444 obufs = (INT16 *) obuf;
445 ibufs = (INT16 *) ibuf;
446 if (dsb->dsound->wfx.wBitsPerSample == 8) {
447 /* 8-bit WAV is unsigned */
448 field = (*ibuf - 128);
449 field -= (*obuf - 128);
450 field = field > 127 ? 127 : field;
451 field = field < -128 ? -128 : field;
454 /* 16-bit WAV is signed */
457 field = field > 32767 ? 32767 : field;
458 field = field < -32768 ? -32768 : field;
463 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
464 obuf = dsb->dsound->buffer;
469 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
471 DWORD size, flen, len, npos, nlen;
472 INT iAdvance = dsb->wfx.nBlockAlign;
473 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
474 /* determine amount of premixed data to cancel */
476 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
477 dsb->primary_mixpos - writepos;
479 TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
481 /* backtrack the mix position */
482 size = primary_done / oAdvance;
483 flen = size * dsb->freqAdjust;
484 len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
485 flen &= (1<<DSOUND_FREQSHIFT)-1;
486 while (dsb->freqAcc < flen) {
488 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
491 npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
492 dsb->buf_mixpos - len;
493 if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
494 /* stop backtracking at startpos */
495 npos = dsb->startpos;
496 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
497 dsb->buf_mixpos - npos;
499 nlen = len / dsb->wfx.nBlockAlign;
500 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
501 nlen *= dsb->dsound->wfx.nBlockAlign;
503 ((dsb->primary_mixpos < nlen) ? dsb->dsound->buflen : 0) +
504 dsb->primary_mixpos - nlen;
507 dsb->freqAcc -= flen;
508 dsb->buf_mixpos = npos;
509 dsb->primary_mixpos = writepos;
511 TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
512 dsb->buf_mixpos, dsb->primary_mixpos, len);
514 if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
517 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
520 DWORD i, size, flen, len, npos, nlen;
521 INT iAdvance = dsb->wfx.nBlockAlign;
522 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
523 /* determine amount of premixed data to cancel */
525 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
526 dsb->buf_mixpos - buf_writepos;
529 WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
530 /* since this is not implemented yet, just cancel *ALL* prebuffering for now
531 * (which is faster anyway when there's only a single secondary buffer) */
532 dsb->dsound->need_remix = TRUE;
535 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
537 EnterCriticalSection(&dsb->lock);
538 if (dsb->state == STATE_PLAYING) {
539 #if 0 /* this may not be quite reliable yet */
540 dsb->need_remix = TRUE;
542 dsb->dsound->need_remix = TRUE;
545 LeaveCriticalSection(&dsb->lock);
548 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
551 /* determine this buffer's write position */
552 DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, dsb->state & dsb->dsound->state, writepos,
553 writepos, dsb->primary_mixpos, dsb->buf_mixpos);
554 /* determine how much already-mixed data exists */
556 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
557 dsb->buf_mixpos - buf_writepos;
559 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
560 dsb->primary_mixpos - writepos;
562 ((dsb->dsound->mixpos < writepos) ? dsb->dsound->buflen : 0) +
563 dsb->dsound->mixpos - writepos;
566 TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
567 TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
568 TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
570 TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
572 /* save write position for non-GETCURRENTPOSITION2... */
573 dsb->playpos = buf_writepos;
575 /* check whether CalcPlayPosition detected a mixing underrun */
576 if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
577 /* it did, but did we have more to play? */
578 if ((dsb->playflags & DSBPLAY_LOOPING) ||
579 (dsb->buf_mixpos < dsb->buflen)) {
580 /* yes, have to recover */
581 ERR("underrun on sound buffer %p\n", dsb);
582 TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
584 dsb->primary_mixpos = writepos;
587 /* determine how far ahead we should mix */
588 if (((dsb->playflags & DSBPLAY_LOOPING) ||
589 (dsb->leadin && (dsb->probably_valid_to != 0))) &&
590 !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
591 /* if this is a streaming buffer, it typically means that
592 * we should defer mixing past probably_valid_to as long
593 * as we can, to avoid unnecessary remixing */
594 /* the heavy-looking calculations shouldn't be that bad,
595 * as any game isn't likely to be have more than 1 or 2
596 * streaming buffers in use at any time anyway... */
597 DWORD probably_valid_left =
598 (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
599 ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
600 dsb->probably_valid_to - buf_writepos;
601 /* check for leadin condition */
602 if ((probably_valid_left == 0) &&
603 (dsb->probably_valid_to == dsb->startpos) &&
605 probably_valid_left = dsb->buflen;
606 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
607 dsb->probably_valid_to, probably_valid_left);
608 /* check whether the app's time is already up */
609 if (probably_valid_left < dsb->writelead) {
610 WARN("probably_valid_to now within writelead, possible streaming underrun\n");
611 /* once we pass the point of no return,
612 * no reason to hold back anymore */
613 dsb->probably_valid_to = (DWORD)-1;
614 /* we just have to go ahead and mix what we have,
615 * there's no telling what the app is thinking anyway */
617 /* adjust for our frequency and our sample size */
618 probably_valid_left = MulDiv(probably_valid_left,
619 1 << DSOUND_FREQSHIFT,
620 dsb->wfx.nBlockAlign * dsb->freqAdjust) *
621 dsb->dsound->wfx.nBlockAlign;
622 /* check whether to clip mix_len */
623 if (probably_valid_left < mixlen) {
624 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
625 mixlen = probably_valid_left;
629 /* cut mixlen with what's already been mixed */
630 if (mixlen < primary_done) {
631 /* huh? and still CalcPlayPosition didn't
632 * detect an underrun? */
633 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
636 len = mixlen - primary_done;
637 TRACE("remaining mixlen=%ld\n", len);
639 if (len < dsb->dsound->fraglen) {
640 /* smaller than a fragment, wait until it gets larger
641 * before we take the mixing overhead */
642 TRACE("mixlen not worth it, deferring mixing\n");
646 /* ok, we know how much to mix, let's go */
647 still_behind = (adv_done > primary_done);
649 slen = dsb->dsound->buflen - dsb->primary_mixpos;
650 if (slen > len) slen = len;
651 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
653 if ((dsb->primary_mixpos < dsb->dsound->mixpos) &&
654 (dsb->primary_mixpos + slen >= dsb->dsound->mixpos))
655 still_behind = FALSE;
657 dsb->primary_mixpos += slen; len -= slen;
658 while (dsb->primary_mixpos >= dsb->dsound->buflen)
659 dsb->primary_mixpos -= dsb->dsound->buflen;
661 if ((dsb->state == STATE_STOPPED) || !slen) break;
663 TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->mixpos);
664 TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
665 /* return how far we think the primary buffer can
666 * advance its underrun detector...*/
667 if (still_behind) return 0;
668 if ((mixlen - len) < primary_done) return 0;
669 slen = ((dsb->primary_mixpos < dsb->dsound->mixpos) ?
670 dsb->dsound->buflen : 0) + dsb->primary_mixpos -
673 /* the primary_done and still_behind checks above should have worked */
674 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
680 static DWORD DSOUND_MixToPrimary(DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
682 INT i, len, maxlen = 0;
683 IDirectSoundBufferImpl *dsb;
685 TRACE("(%ld,%ld,%ld)\n", playpos, writepos, mixlen);
686 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
687 dsb = dsound->buffers[i];
689 if (!dsb || !(ICOM_VTBL(dsb)))
691 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
692 TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
693 EnterCriticalSection(&(dsb->lock));
694 if (dsb->state == STATE_STOPPING) {
695 DSOUND_MixCancel(dsb, writepos, TRUE);
696 dsb->state = STATE_STOPPED;
698 if ((dsb->state == STATE_STARTING) || recover) {
699 dsb->primary_mixpos = writepos;
700 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
701 dsb->need_remix = FALSE;
703 else if (dsb->need_remix) {
704 DSOUND_MixCancel(dsb, writepos, TRUE);
705 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
706 dsb->need_remix = FALSE;
708 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
709 if (dsb->state == STATE_STARTING)
710 dsb->state = STATE_PLAYING;
711 maxlen = (len > maxlen) ? len : maxlen;
713 LeaveCriticalSection(&(dsb->lock));
720 static void DSOUND_MixReset(DWORD writepos)
723 IDirectSoundBufferImpl *dsb;
726 TRACE("(%ld)\n", writepos);
728 /* the sound of silence */
729 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
731 /* reset all buffer mix positions */
732 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
733 dsb = dsound->buffers[i];
735 if (!dsb || !(ICOM_VTBL(dsb)))
737 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
738 TRACE("Resetting %p\n", dsb);
739 EnterCriticalSection(&(dsb->lock));
740 if (dsb->state == STATE_STOPPING) {
741 dsb->state = STATE_STOPPED;
743 else if (dsb->state == STATE_STARTING) {
746 DSOUND_MixCancel(dsb, writepos, FALSE);
747 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
748 dsb->need_remix = FALSE;
750 LeaveCriticalSection(&(dsb->lock));
754 /* wipe out premixed data */
755 if (dsound->mixpos < writepos) {
756 memset(dsound->buffer + writepos, nfiller, dsound->buflen - writepos);
757 memset(dsound->buffer, nfiller, dsound->mixpos);
759 memset(dsound->buffer + writepos, nfiller, dsound->mixpos - writepos);
762 /* reset primary mix position */
763 dsound->mixpos = writepos;
766 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
768 if (dsound->need_remix) {
769 DSOUND_MixReset(writepos);
770 dsound->need_remix = FALSE;
771 /* maximize Half-Life performance */
772 dsound->prebuf = ds_snd_queue_min;
773 dsound->precount = 0;
776 if (dsound->precount >= 4) {
777 if (dsound->prebuf < ds_snd_queue_max)
779 dsound->precount = 0;
782 TRACE("premix adjust: %d\n", dsound->prebuf);
785 void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
787 if (mixq + dsound->pwqueue > ds_hel_queue) mixq = ds_hel_queue - dsound->pwqueue;
788 TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
789 for (; mixq; mixq--) {
790 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
792 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
797 /* #define SYNC_CALLBACK */
799 void DSOUND_PerformMix(void)
805 RtlAcquireResourceShared(&(dsound->lock), TRUE);
807 if (!dsound || !dsound->ref) {
808 /* seems the dsound object is currently being released */
809 RtlReleaseResource(&(dsound->lock));
813 /* the sound of silence */
814 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
816 /* whether the primary is forced to play even without secondary buffers */
817 forced = ((dsound->state == STATE_PLAYING) || (dsound->state == STATE_STARTING));
819 TRACE("entering at %ld\n", GetTickCount());
820 if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
821 BOOL paused = ((dsound->state == STATE_STOPPED) || (dsound->state == STATE_STARTING));
822 /* FIXME: document variables */
823 DWORD playpos, writepos, inq, maxq, frag;
825 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, &writepos);
827 RtlReleaseResource(&(dsound->lock));
830 /* Well, we *could* do Just-In-Time mixing using the writepos,
831 * but that's a little bit ambitious and unnecessary... */
832 /* rather add our safety margin to the writepos, if we're playing */
834 writepos += dsound->writelead;
835 while (writepos >= dsound->buflen)
836 writepos -= dsound->buflen;
837 } else writepos = playpos;
840 playpos = dsound->pwplay * dsound->fraglen;
843 writepos += ds_hel_margin * dsound->fraglen;
844 while (writepos >= dsound->buflen)
845 writepos -= dsound->buflen;
848 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld\n",
849 playpos,writepos,dsound->playpos,dsound->mixpos);
850 /* wipe out just-played sound data */
851 if (playpos < dsound->playpos) {
852 memset(dsound->buffer + dsound->playpos, nfiller, dsound->buflen - dsound->playpos);
853 memset(dsound->buffer, nfiller, playpos);
855 memset(dsound->buffer + dsound->playpos, nfiller, playpos - dsound->playpos);
857 dsound->playpos = playpos;
859 EnterCriticalSection(&(dsound->mixlock));
861 /* reset mixing if necessary */
862 DSOUND_CheckReset(dsound, writepos);
864 /* check how much prebuffering is left */
865 inq = dsound->mixpos;
867 inq += dsound->buflen;
870 /* find the maximum we can prebuffer */
874 maxq += dsound->buflen;
876 } else maxq = dsound->buflen;
878 /* clip maxq to dsound->prebuf */
879 frag = dsound->prebuf * dsound->fraglen;
880 if (maxq > frag) maxq = frag;
882 /* check for consistency */
884 /* the playback position must have passed our last
885 * mixed position, i.e. it's an underrun, or we have
886 * nothing more to play */
887 TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
889 /* stop the playback now, to allow buffers to refill */
890 if (dsound->state == STATE_PLAYING) {
891 dsound->state = STATE_STARTING;
893 else if (dsound->state == STATE_STOPPING) {
894 dsound->state = STATE_STOPPED;
897 /* how can we have an underrun if we aren't playing? */
898 WARN("unexpected primary state (%ld)\n", dsound->state);
901 /* DSOUND_callback may need this lock */
902 LeaveCriticalSection(&(dsound->mixlock));
904 DSOUND_PrimaryStop(dsound);
906 EnterCriticalSection(&(dsound->mixlock));
909 /* the Stop is supposed to reset play position to beginning of buffer */
910 /* unfortunately, OSS is not able to do so, so get current pointer */
911 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, NULL);
913 LeaveCriticalSection(&(dsound->mixlock));
914 RtlReleaseResource(&(dsound->lock));
918 playpos = dsound->pwplay * dsound->fraglen;
921 dsound->playpos = playpos;
922 dsound->mixpos = writepos;
924 maxq = dsound->buflen;
925 if (maxq > frag) maxq = frag;
926 memset(dsound->buffer, nfiller, dsound->buflen);
931 frag = DSOUND_MixToPrimary(playpos, writepos, maxq, paused);
932 if (forced) frag = maxq - inq;
933 dsound->mixpos += frag;
934 while (dsound->mixpos >= dsound->buflen)
935 dsound->mixpos -= dsound->buflen;
938 /* buffers have been filled, restart playback */
939 if (dsound->state == STATE_STARTING) {
940 dsound->state = STATE_PLAYING;
942 else if (dsound->state == STATE_STOPPED) {
943 /* the dsound is supposed to play if there's something to play
944 * even if it is reported as stopped, so don't let this confuse you */
945 dsound->state = STATE_STOPPING;
947 LeaveCriticalSection(&(dsound->mixlock));
949 DSOUND_PrimaryPlay(dsound);
950 TRACE("starting playback\n");
954 LeaveCriticalSection(&(dsound->mixlock));
956 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
957 if (dsound->state == STATE_STARTING) {
958 DSOUND_PrimaryPlay(dsound);
959 dsound->state = STATE_PLAYING;
961 else if (dsound->state == STATE_STOPPING) {
962 DSOUND_PrimaryStop(dsound);
963 dsound->state = STATE_STOPPED;
966 TRACE("completed processing at %ld\n", GetTickCount());
967 RtlReleaseResource(&(dsound->lock));
970 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
973 ERR("dsound died without killing us?\n");
974 timeKillEvent(timerID);
975 timeEndPeriod(DS_TIME_RES);
983 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
985 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
986 TRACE("entering at %ld, msg=%08x(%s)\n", GetTickCount(), msg,
987 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
988 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
989 if (msg == MM_WOM_DONE) {
990 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
991 if (This->pwqueue == (DWORD)-1) {
992 TRACE("completed due to reset\n");
995 /* it could be a bad idea to enter critical section here... if there's lock contention,
996 * the resulting scheduling delays might obstruct the winmm player thread */
998 EnterCriticalSection(&(This->mixlock));
1000 /* retrieve current values */
1001 fraglen = dsound->fraglen;
1002 buflen = dsound->buflen;
1003 pwplay = dsound->pwplay;
1004 playpos = pwplay * fraglen;
1005 mixpos = dsound->mixpos;
1006 /* check remaining mixed data */
1007 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1008 mixq = inq / fraglen;
1009 if ((inq - (mixq * fraglen)) > 0) mixq++;
1010 /* complete the playing buffer */
1011 TRACE("done playing primary pos=%ld\n", playpos);
1013 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1014 /* write new values */
1015 dsound->pwplay = pwplay;
1017 /* queue new buffer if we have data for it */
1018 if (inq>1) DSOUND_WaveQueue(This, inq-1);
1019 #ifdef SYNC_CALLBACK
1020 LeaveCriticalSection(&(This->mixlock));
1023 TRACE("completed\n");