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 */
339 /* Been seeing segfaults in malloc() for some reason... */
340 TRACE("allocating buffer (size = %d)\n", len);
341 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
344 TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
346 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
347 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
348 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
349 DSOUND_MixerVol(dsb, ibuf, len);
351 obuf = dsb->dsound->buffer + writepos;
352 for (i = 0; i < len; i += advance) {
353 obufs = (INT16 *) obuf;
354 ibufs = (INT16 *) ibuf;
355 if (dsb->dsound->wfx.wBitsPerSample == 8) {
356 /* 8-bit WAV is unsigned */
357 field = (*ibuf - 128);
358 field += (*obuf - 128);
359 field = field > 127 ? 127 : field;
360 field = field < -128 ? -128 : field;
363 /* 16-bit WAV is signed */
366 field = field > 32767 ? 32767 : field;
367 field = field < -32768 ? -32768 : field;
372 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
373 obuf = dsb->dsound->buffer;
377 if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
378 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
379 * not the MIX position... but if the sound buffer is bigger than our prebuffering
380 * (which must be the case for the streaming buffers that need this hack anyway)
381 * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
385 dsb->buf_mixpos += ilen;
387 if (dsb->buf_mixpos >= dsb->buflen) {
388 if (dsb->playflags & DSBPLAY_LOOPING) {
390 while (dsb->buf_mixpos >= dsb->buflen)
391 dsb->buf_mixpos -= dsb->buflen;
392 if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
393 dsb->leadin = FALSE; /* HACK: see above */
400 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
403 INT advance = dsb->dsound->wfx.wBitsPerSample >> 3;
404 BYTE *buf, *ibuf, *obuf;
405 INT16 *ibufs, *obufs;
407 len &= ~3; /* 4 byte alignment */
409 TRACE("allocating buffer (size = %ld)\n", len);
410 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
413 TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
415 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
416 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
417 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
418 DSOUND_MixerVol(dsb, ibuf, len);
420 /* subtract instead of add, to phase out premixed data */
421 obuf = dsb->dsound->buffer + writepos;
422 for (i = 0; i < len; i += advance) {
423 obufs = (INT16 *) obuf;
424 ibufs = (INT16 *) ibuf;
425 if (dsb->dsound->wfx.wBitsPerSample == 8) {
426 /* 8-bit WAV is unsigned */
427 field = (*ibuf - 128);
428 field -= (*obuf - 128);
429 field = field > 127 ? 127 : field;
430 field = field < -128 ? -128 : field;
433 /* 16-bit WAV is signed */
436 field = field > 32767 ? 32767 : field;
437 field = field < -32768 ? -32768 : field;
442 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
443 obuf = dsb->dsound->buffer;
448 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
450 DWORD size, flen, len, npos, nlen;
451 INT iAdvance = dsb->wfx.nBlockAlign;
452 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
453 /* determine amount of premixed data to cancel */
455 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
456 dsb->primary_mixpos - writepos;
458 TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
460 /* backtrack the mix position */
461 size = primary_done / oAdvance;
462 flen = size * dsb->freqAdjust;
463 len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
464 flen &= (1<<DSOUND_FREQSHIFT)-1;
465 while (dsb->freqAcc < flen) {
467 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
470 npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
471 dsb->buf_mixpos - len;
472 if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
473 /* stop backtracking at startpos */
474 npos = dsb->startpos;
475 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
476 dsb->buf_mixpos - npos;
478 nlen = len / dsb->wfx.nBlockAlign;
479 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
480 nlen *= dsb->dsound->wfx.nBlockAlign;
482 ((dsb->primary_mixpos < nlen) ? dsb->dsound->buflen : 0) +
483 dsb->primary_mixpos - nlen;
486 dsb->freqAcc -= flen;
487 dsb->buf_mixpos = npos;
488 dsb->primary_mixpos = writepos;
490 TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
491 dsb->buf_mixpos, dsb->primary_mixpos, len);
493 if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
496 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
499 DWORD i, size, flen, len, npos, nlen;
500 INT iAdvance = dsb->wfx.nBlockAlign;
501 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
502 /* determine amount of premixed data to cancel */
504 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
505 dsb->buf_mixpos - buf_writepos;
508 WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
509 /* since this is not implemented yet, just cancel *ALL* prebuffering for now
510 * (which is faster anyway when there's only a single secondary buffer) */
511 dsb->dsound->need_remix = TRUE;
514 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
516 EnterCriticalSection(&dsb->lock);
517 if (dsb->state == STATE_PLAYING) {
518 #if 0 /* this may not be quite reliable yet */
519 dsb->need_remix = TRUE;
521 dsb->dsound->need_remix = TRUE;
524 LeaveCriticalSection(&dsb->lock);
527 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
530 /* determine this buffer's write position */
531 DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, dsb->state & dsb->dsound->state, writepos,
532 writepos, dsb->primary_mixpos, dsb->buf_mixpos);
533 /* determine how much already-mixed data exists */
535 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
536 dsb->buf_mixpos - buf_writepos;
538 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
539 dsb->primary_mixpos - writepos;
541 ((dsb->dsound->mixpos < writepos) ? dsb->dsound->buflen : 0) +
542 dsb->dsound->mixpos - writepos;
544 ((buf_writepos < dsb->playpos) ? dsb->buflen : 0) +
545 buf_writepos - dsb->playpos;
546 DWORD buf_left = dsb->buflen - buf_writepos;
549 TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
550 TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
551 TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
553 TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
555 /* check for notification positions */
556 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
557 dsb->state != STATE_STARTING) {
558 DSOUND_CheckEvent(dsb, played);
561 /* save write position for non-GETCURRENTPOSITION2... */
562 dsb->playpos = buf_writepos;
564 /* check whether CalcPlayPosition detected a mixing underrun */
565 if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
566 /* it did, but did we have more to play? */
567 if ((dsb->playflags & DSBPLAY_LOOPING) ||
568 (dsb->buf_mixpos < dsb->buflen)) {
569 /* yes, have to recover */
570 ERR("underrun on sound buffer %p\n", dsb);
571 TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
573 dsb->primary_mixpos = writepos;
576 /* determine how far ahead we should mix */
577 if (((dsb->playflags & DSBPLAY_LOOPING) ||
578 (dsb->leadin && (dsb->probably_valid_to != 0))) &&
579 !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
580 /* if this is a streaming buffer, it typically means that
581 * we should defer mixing past probably_valid_to as long
582 * as we can, to avoid unnecessary remixing */
583 /* the heavy-looking calculations shouldn't be that bad,
584 * as any game isn't likely to be have more than 1 or 2
585 * streaming buffers in use at any time anyway... */
586 DWORD probably_valid_left =
587 (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
588 ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
589 dsb->probably_valid_to - buf_writepos;
590 /* check for leadin condition */
591 if ((probably_valid_left == 0) &&
592 (dsb->probably_valid_to == dsb->startpos) &&
594 probably_valid_left = dsb->buflen;
595 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
596 dsb->probably_valid_to, probably_valid_left);
597 /* check whether the app's time is already up */
598 if (probably_valid_left < dsb->writelead) {
599 WARN("probably_valid_to now within writelead, possible streaming underrun\n");
600 /* once we pass the point of no return,
601 * no reason to hold back anymore */
602 dsb->probably_valid_to = (DWORD)-1;
603 /* we just have to go ahead and mix what we have,
604 * there's no telling what the app is thinking anyway */
606 /* adjust for our frequency and our sample size */
607 probably_valid_left = MulDiv(probably_valid_left,
608 1 << DSOUND_FREQSHIFT,
609 dsb->wfx.nBlockAlign * dsb->freqAdjust) *
610 dsb->dsound->wfx.nBlockAlign;
611 /* check whether to clip mix_len */
612 if (probably_valid_left < mixlen) {
613 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
614 mixlen = probably_valid_left;
618 /* cut mixlen with what's already been mixed */
619 if (mixlen < primary_done) {
620 /* huh? and still CalcPlayPosition didn't
621 * detect an underrun? */
622 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
625 len = mixlen - primary_done;
626 TRACE("remaining mixlen=%ld\n", len);
628 if (len < dsb->dsound->fraglen) {
629 /* smaller than a fragment, wait until it gets larger
630 * before we take the mixing overhead */
631 TRACE("mixlen not worth it, deferring mixing\n");
636 /* ok, we know how much to mix, let's go */
637 still_behind = (adv_done > primary_done);
639 slen = dsb->dsound->buflen - dsb->primary_mixpos;
640 if (slen > len) slen = len;
641 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
643 if ((dsb->primary_mixpos < dsb->dsound->mixpos) &&
644 (dsb->primary_mixpos + slen >= dsb->dsound->mixpos))
645 still_behind = FALSE;
647 dsb->primary_mixpos += slen; len -= slen;
648 while (dsb->primary_mixpos >= dsb->dsound->buflen)
649 dsb->primary_mixpos -= dsb->dsound->buflen;
651 if ((dsb->state == STATE_STOPPED) || !slen) break;
653 TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->mixpos);
654 TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
657 /* check if buffer should be considered complete */
658 if (buf_left < dsb->writelead &&
659 !(dsb->playflags & DSBPLAY_LOOPING)) {
660 dsb->state = STATE_STOPPED;
662 dsb->last_playpos = 0;
665 DSOUND_CheckEvent(dsb, buf_left);
668 /* return how far we think the primary buffer can
669 * advance its underrun detector...*/
670 if (still_behind) return 0;
671 if ((mixlen - len) < primary_done) return 0;
672 slen = ((dsb->primary_mixpos < dsb->dsound->mixpos) ?
673 dsb->dsound->buflen : 0) + dsb->primary_mixpos -
676 /* the primary_done and still_behind checks above should have worked */
677 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
683 static DWORD DSOUND_MixToPrimary(DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
685 INT i, len, maxlen = 0;
686 IDirectSoundBufferImpl *dsb;
688 TRACE("(%ld,%ld,%ld)\n", playpos, writepos, mixlen);
689 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
690 dsb = dsound->buffers[i];
692 if (!dsb || !(ICOM_VTBL(dsb)))
694 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
695 TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
696 EnterCriticalSection(&(dsb->lock));
697 if (dsb->state == STATE_STOPPING) {
698 DSOUND_MixCancel(dsb, writepos, TRUE);
699 dsb->state = STATE_STOPPED;
700 DSOUND_CheckEvent(dsb, 0);
702 if ((dsb->state == STATE_STARTING) || recover) {
703 dsb->primary_mixpos = writepos;
704 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
705 dsb->need_remix = FALSE;
707 else if (dsb->need_remix) {
708 DSOUND_MixCancel(dsb, writepos, TRUE);
709 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
710 dsb->need_remix = FALSE;
712 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
713 if (dsb->state == STATE_STARTING)
714 dsb->state = STATE_PLAYING;
715 maxlen = (len > maxlen) ? len : maxlen;
717 LeaveCriticalSection(&(dsb->lock));
724 static void DSOUND_MixReset(DWORD writepos)
727 IDirectSoundBufferImpl *dsb;
730 TRACE("(%ld)\n", writepos);
732 /* the sound of silence */
733 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
735 /* reset all buffer mix positions */
736 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
737 dsb = dsound->buffers[i];
739 if (!dsb || !(ICOM_VTBL(dsb)))
741 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
742 TRACE("Resetting %p\n", dsb);
743 EnterCriticalSection(&(dsb->lock));
744 if (dsb->state == STATE_STOPPING) {
745 dsb->state = STATE_STOPPED;
747 else if (dsb->state == STATE_STARTING) {
750 DSOUND_MixCancel(dsb, writepos, FALSE);
751 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
752 dsb->need_remix = FALSE;
754 LeaveCriticalSection(&(dsb->lock));
758 /* wipe out premixed data */
759 if (dsound->mixpos < writepos) {
760 memset(dsound->buffer + writepos, nfiller, dsound->buflen - writepos);
761 memset(dsound->buffer, nfiller, dsound->mixpos);
763 memset(dsound->buffer + writepos, nfiller, dsound->mixpos - writepos);
766 /* reset primary mix position */
767 dsound->mixpos = writepos;
770 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
772 if (dsound->need_remix) {
773 DSOUND_MixReset(writepos);
774 dsound->need_remix = FALSE;
775 /* maximize Half-Life performance */
776 dsound->prebuf = ds_snd_queue_min;
777 dsound->precount = 0;
780 if (dsound->precount >= 4) {
781 if (dsound->prebuf < ds_snd_queue_max)
783 dsound->precount = 0;
786 TRACE("premix adjust: %d\n", dsound->prebuf);
789 void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
791 if (mixq + dsound->pwqueue > ds_hel_queue) mixq = ds_hel_queue - dsound->pwqueue;
792 TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
793 for (; mixq; mixq--) {
794 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
796 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
801 /* #define SYNC_CALLBACK */
803 void DSOUND_PerformMix(void)
809 RtlAcquireResourceShared(&(dsound->lock), TRUE);
811 if (!dsound || !dsound->ref) {
812 /* seems the dsound object is currently being released */
813 RtlReleaseResource(&(dsound->lock));
817 /* the sound of silence */
818 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
820 /* whether the primary is forced to play even without secondary buffers */
821 forced = ((dsound->state == STATE_PLAYING) || (dsound->state == STATE_STARTING));
823 TRACE("entering at %ld\n", GetTickCount());
824 if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
825 BOOL paused = ((dsound->state == STATE_STOPPED) || (dsound->state == STATE_STARTING));
826 /* FIXME: document variables */
827 DWORD playpos, writepos, inq, maxq, frag;
829 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, &writepos);
831 RtlReleaseResource(&(dsound->lock));
834 /* Well, we *could* do Just-In-Time mixing using the writepos,
835 * but that's a little bit ambitious and unnecessary... */
836 /* rather add our safety margin to the writepos, if we're playing */
838 writepos += dsound->writelead;
839 while (writepos >= dsound->buflen)
840 writepos -= dsound->buflen;
841 } else writepos = playpos;
844 playpos = dsound->pwplay * dsound->fraglen;
847 writepos += ds_hel_margin * dsound->fraglen;
848 while (writepos >= dsound->buflen)
849 writepos -= dsound->buflen;
852 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld\n",
853 playpos,writepos,dsound->playpos,dsound->mixpos);
854 /* wipe out just-played sound data */
855 if (playpos < dsound->playpos) {
856 memset(dsound->buffer + dsound->playpos, nfiller, dsound->buflen - dsound->playpos);
857 memset(dsound->buffer, nfiller, playpos);
859 memset(dsound->buffer + dsound->playpos, nfiller, playpos - dsound->playpos);
861 dsound->playpos = playpos;
863 EnterCriticalSection(&(dsound->mixlock));
865 /* reset mixing if necessary */
866 DSOUND_CheckReset(dsound, writepos);
868 /* check how much prebuffering is left */
869 inq = dsound->mixpos;
871 inq += dsound->buflen;
874 /* find the maximum we can prebuffer */
878 maxq += dsound->buflen;
880 } else maxq = dsound->buflen;
882 /* clip maxq to dsound->prebuf */
883 frag = dsound->prebuf * dsound->fraglen;
884 if (maxq > frag) maxq = frag;
886 /* check for consistency */
888 /* the playback position must have passed our last
889 * mixed position, i.e. it's an underrun, or we have
890 * nothing more to play */
891 TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
893 /* stop the playback now, to allow buffers to refill */
894 if (dsound->state == STATE_PLAYING) {
895 dsound->state = STATE_STARTING;
897 else if (dsound->state == STATE_STOPPING) {
898 dsound->state = STATE_STOPPED;
901 /* how can we have an underrun if we aren't playing? */
902 WARN("unexpected primary state (%ld)\n", dsound->state);
905 /* DSOUND_callback may need this lock */
906 LeaveCriticalSection(&(dsound->mixlock));
908 DSOUND_PrimaryStop(dsound);
910 EnterCriticalSection(&(dsound->mixlock));
913 /* the Stop is supposed to reset play position to beginning of buffer */
914 /* unfortunately, OSS is not able to do so, so get current pointer */
915 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, NULL);
917 LeaveCriticalSection(&(dsound->mixlock));
918 RtlReleaseResource(&(dsound->lock));
922 playpos = dsound->pwplay * dsound->fraglen;
925 dsound->playpos = playpos;
926 dsound->mixpos = writepos;
928 maxq = dsound->buflen;
929 if (maxq > frag) maxq = frag;
930 memset(dsound->buffer, nfiller, dsound->buflen);
935 frag = DSOUND_MixToPrimary(playpos, writepos, maxq, paused);
936 if (forced) frag = maxq - inq;
937 dsound->mixpos += frag;
938 while (dsound->mixpos >= dsound->buflen)
939 dsound->mixpos -= dsound->buflen;
942 /* buffers have been filled, restart playback */
943 if (dsound->state == STATE_STARTING) {
944 dsound->state = STATE_PLAYING;
946 else if (dsound->state == STATE_STOPPED) {
947 /* the dsound is supposed to play if there's something to play
948 * even if it is reported as stopped, so don't let this confuse you */
949 dsound->state = STATE_STOPPING;
951 LeaveCriticalSection(&(dsound->mixlock));
953 DSOUND_PrimaryPlay(dsound);
954 TRACE("starting playback\n");
958 LeaveCriticalSection(&(dsound->mixlock));
960 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
961 if (dsound->state == STATE_STARTING) {
962 DSOUND_PrimaryPlay(dsound);
963 dsound->state = STATE_PLAYING;
965 else if (dsound->state == STATE_STOPPING) {
966 DSOUND_PrimaryStop(dsound);
967 dsound->state = STATE_STOPPED;
970 TRACE("completed processing at %ld\n", GetTickCount());
971 RtlReleaseResource(&(dsound->lock));
974 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
977 ERR("dsound died without killing us?\n");
978 timeKillEvent(timerID);
979 timeEndPeriod(DS_TIME_RES);
987 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
989 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
990 TRACE("entering at %ld, msg=%08x(%s)\n", GetTickCount(), msg,
991 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
992 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
993 if (msg == MM_WOM_DONE) {
994 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
995 if (This->pwqueue == (DWORD)-1) {
996 TRACE("completed due to reset\n");
999 /* it could be a bad idea to enter critical section here... if there's lock contention,
1000 * the resulting scheduling delays might obstruct the winmm player thread */
1001 #ifdef SYNC_CALLBACK
1002 EnterCriticalSection(&(This->mixlock));
1004 /* retrieve current values */
1005 fraglen = dsound->fraglen;
1006 buflen = dsound->buflen;
1007 pwplay = dsound->pwplay;
1008 playpos = pwplay * fraglen;
1009 mixpos = dsound->mixpos;
1010 /* check remaining mixed data */
1011 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1012 mixq = inq / fraglen;
1013 if ((inq - (mixq * fraglen)) > 0) mixq++;
1014 /* complete the playing buffer */
1015 TRACE("done playing primary pos=%ld\n", playpos);
1017 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1018 /* write new values */
1019 dsound->pwplay = pwplay;
1021 /* queue new buffer if we have data for it */
1022 if (inq>1) DSOUND_WaveQueue(This, inq-1);
1023 #ifdef SYNC_CALLBACK
1024 LeaveCriticalSection(&(This->mixlock));
1027 TRACE("completed\n");