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->notify || dsb->notify->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->notify->nrofnotifies ; i++) {
88 event = dsb->notify->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)
261 INT16 *bps = (INT16 *) buf;
263 TRACE("(%p,%p,%d)\n",dsb,buf,len);
264 TRACE("left = %lx, right = %lx\n", dsb->cvolpan.dwTotalLeftAmpFactor,
265 dsb->cvolpan.dwTotalRightAmpFactor);
267 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->cvolpan.lPan == 0)) &&
268 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->cvolpan.lVolume == 0)) &&
269 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
270 return; /* Nothing to do */
272 /* If we end up with some bozo coder using panning or 3D sound */
273 /* with a mono primary buffer, it could sound very weird using */
274 /* this method. Oh well, tough patooties. */
276 switch (dsb->dsound->wfx.wBitsPerSample) {
278 /* 8-bit WAV is unsigned, but we need to operate */
279 /* on signed data for this to work properly */
280 switch (dsb->dsound->wfx.nChannels) {
282 for (i = 0; i < len; i++) {
283 INT val = *bpc - 128;
284 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
290 for (i = 0; i < len; i+=2) {
291 INT val = *bpc - 128;
292 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
295 val = (val * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
301 FIXME("doesn't support %d channels\n", dsb->dsound->wfx.nChannels);
306 /* 16-bit WAV is signed -- much better */
307 switch (dsb->dsound->wfx.nChannels) {
309 for (i = 0; i < len; i += 2) {
310 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
315 for (i = 0; i < len; i += 4) {
316 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
318 *bps = (*bps * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
323 FIXME("doesn't support %d channels\n", dsb->dsound->wfx.nChannels);
328 FIXME("doesn't support %d bit samples\n", dsb->dsound->wfx.wBitsPerSample);
333 static void *tmp_buffer;
334 static size_t tmp_buffer_len = 0;
336 static void *DSOUND_tmpbuffer(size_t len)
338 if (len>tmp_buffer_len) {
339 void *new_buffer = realloc(tmp_buffer, len);
341 tmp_buffer = new_buffer;
342 tmp_buffer_len = len;
349 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
351 INT i, len, ilen, temp, field, nBlockAlign;
352 INT advance = dsb->dsound->wfx.wBitsPerSample >> 3;
353 BYTE *buf, *ibuf, *obuf;
354 INT16 *ibufs, *obufs;
356 TRACE("%p,%ld,%ld)\n",dsb,writepos,fraglen);
359 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
360 temp = MulDiv(dsb->dsound->wfx.nAvgBytesPerSec, dsb->buflen,
361 dsb->nAvgBytesPerSec) -
362 MulDiv(dsb->dsound->wfx.nAvgBytesPerSec, dsb->buf_mixpos,
363 dsb->nAvgBytesPerSec);
364 len = (len > temp) ? temp : len;
366 nBlockAlign = dsb->dsound->wfx.nBlockAlign;
367 len = len / nBlockAlign * nBlockAlign; /* data alignment */
370 /* This should only happen if we aren't looping and temp < nBlockAlign */
374 /* Been seeing segfaults in malloc() for some reason... */
375 TRACE("allocating buffer (size = %d)\n", len);
376 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
379 TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
381 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
382 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
383 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
384 DSOUND_MixerVol(dsb, ibuf, len);
386 obuf = dsb->dsound->buffer + writepos;
387 for (i = 0; i < len; i += advance) {
388 obufs = (INT16 *) obuf;
389 ibufs = (INT16 *) ibuf;
390 if (dsb->dsound->wfx.wBitsPerSample == 8) {
391 /* 8-bit WAV is unsigned */
392 field = (*ibuf - 128);
393 field += (*obuf - 128);
394 field = field > 127 ? 127 : field;
395 field = field < -128 ? -128 : field;
398 /* 16-bit WAV is signed */
401 field = field > 32767 ? 32767 : field;
402 field = field < -32768 ? -32768 : field;
407 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
408 obuf = dsb->dsound->buffer;
412 if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
413 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
414 * not the MIX position... but if the sound buffer is bigger than our prebuffering
415 * (which must be the case for the streaming buffers that need this hack anyway)
416 * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
420 dsb->buf_mixpos += ilen;
422 if (dsb->buf_mixpos >= dsb->buflen) {
423 if (dsb->playflags & DSBPLAY_LOOPING) {
425 while (dsb->buf_mixpos >= dsb->buflen)
426 dsb->buf_mixpos -= dsb->buflen;
427 if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
428 dsb->leadin = FALSE; /* HACK: see above */
435 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
437 INT i, ilen, field, nBlockAlign;
438 INT advance = dsb->dsound->wfx.wBitsPerSample >> 3;
439 BYTE *buf, *ibuf, *obuf;
440 INT16 *ibufs, *obufs;
442 nBlockAlign = dsb->dsound->wfx.nBlockAlign;
443 len = len / nBlockAlign * nBlockAlign; /* data 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;
580 ((buf_writepos < dsb->playpos) ? dsb->buflen : 0) +
581 buf_writepos - dsb->playpos;
582 DWORD buf_left = dsb->buflen - buf_writepos;
585 TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
586 TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
587 TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
589 TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
591 /* check for notification positions */
592 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
593 dsb->state != STATE_STARTING) {
594 DSOUND_CheckEvent(dsb, played);
597 /* save write position for non-GETCURRENTPOSITION2... */
598 dsb->playpos = buf_writepos;
600 /* check whether CalcPlayPosition detected a mixing underrun */
601 if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
602 /* it did, but did we have more to play? */
603 if ((dsb->playflags & DSBPLAY_LOOPING) ||
604 (dsb->buf_mixpos < dsb->buflen)) {
605 /* yes, have to recover */
606 ERR("underrun on sound buffer %p\n", dsb);
607 TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
609 dsb->primary_mixpos = writepos;
612 /* determine how far ahead we should mix */
613 if (((dsb->playflags & DSBPLAY_LOOPING) ||
614 (dsb->leadin && (dsb->probably_valid_to != 0))) &&
615 !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
616 /* if this is a streaming buffer, it typically means that
617 * we should defer mixing past probably_valid_to as long
618 * as we can, to avoid unnecessary remixing */
619 /* the heavy-looking calculations shouldn't be that bad,
620 * as any game isn't likely to be have more than 1 or 2
621 * streaming buffers in use at any time anyway... */
622 DWORD probably_valid_left =
623 (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
624 ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
625 dsb->probably_valid_to - buf_writepos;
626 /* check for leadin condition */
627 if ((probably_valid_left == 0) &&
628 (dsb->probably_valid_to == dsb->startpos) &&
630 probably_valid_left = dsb->buflen;
631 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
632 dsb->probably_valid_to, probably_valid_left);
633 /* check whether the app's time is already up */
634 if (probably_valid_left < dsb->writelead) {
635 WARN("probably_valid_to now within writelead, possible streaming underrun\n");
636 /* once we pass the point of no return,
637 * no reason to hold back anymore */
638 dsb->probably_valid_to = (DWORD)-1;
639 /* we just have to go ahead and mix what we have,
640 * there's no telling what the app is thinking anyway */
642 /* adjust for our frequency and our sample size */
643 probably_valid_left = MulDiv(probably_valid_left,
644 1 << DSOUND_FREQSHIFT,
645 dsb->wfx.nBlockAlign * dsb->freqAdjust) *
646 dsb->dsound->wfx.nBlockAlign;
647 /* check whether to clip mix_len */
648 if (probably_valid_left < mixlen) {
649 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
650 mixlen = probably_valid_left;
654 /* cut mixlen with what's already been mixed */
655 if (mixlen < primary_done) {
656 /* huh? and still CalcPlayPosition didn't
657 * detect an underrun? */
658 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
661 len = mixlen - primary_done;
662 TRACE("remaining mixlen=%ld\n", len);
664 if (len < dsb->dsound->fraglen) {
665 /* smaller than a fragment, wait until it gets larger
666 * before we take the mixing overhead */
667 TRACE("mixlen not worth it, deferring mixing\n");
672 /* ok, we know how much to mix, let's go */
673 still_behind = (adv_done > primary_done);
675 slen = dsb->dsound->buflen - dsb->primary_mixpos;
676 if (slen > len) slen = len;
677 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
679 if ((dsb->primary_mixpos < dsb->dsound->mixpos) &&
680 (dsb->primary_mixpos + slen >= dsb->dsound->mixpos))
681 still_behind = FALSE;
683 dsb->primary_mixpos += slen; len -= slen;
684 while (dsb->primary_mixpos >= dsb->dsound->buflen)
685 dsb->primary_mixpos -= dsb->dsound->buflen;
687 if ((dsb->state == STATE_STOPPED) || !slen) break;
689 TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->mixpos);
690 TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
693 /* check if buffer should be considered complete */
694 if (buf_left < dsb->writelead &&
695 !(dsb->playflags & DSBPLAY_LOOPING)) {
696 dsb->state = STATE_STOPPED;
698 dsb->last_playpos = 0;
701 DSOUND_CheckEvent(dsb, buf_left);
704 /* return how far we think the primary buffer can
705 * advance its underrun detector...*/
706 if (still_behind) return 0;
707 if ((mixlen - len) < primary_done) return 0;
708 slen = ((dsb->primary_mixpos < dsb->dsound->mixpos) ?
709 dsb->dsound->buflen : 0) + dsb->primary_mixpos -
712 /* the primary_done and still_behind checks above should have worked */
713 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
719 static DWORD DSOUND_MixToPrimary(DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
721 INT i, len, maxlen = 0;
722 IDirectSoundBufferImpl *dsb;
724 TRACE("(%ld,%ld,%ld)\n", playpos, writepos, mixlen);
725 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
726 dsb = dsound->buffers[i];
728 if (!dsb || !dsb->lpVtbl)
730 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
731 TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
732 EnterCriticalSection(&(dsb->lock));
733 if (dsb->state == STATE_STOPPING) {
734 DSOUND_MixCancel(dsb, writepos, TRUE);
735 dsb->state = STATE_STOPPED;
736 DSOUND_CheckEvent(dsb, 0);
738 if ((dsb->state == STATE_STARTING) || recover) {
739 dsb->primary_mixpos = writepos;
740 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
741 dsb->need_remix = FALSE;
743 else if (dsb->need_remix) {
744 DSOUND_MixCancel(dsb, writepos, TRUE);
745 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
746 dsb->need_remix = FALSE;
748 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
749 if (dsb->state == STATE_STARTING)
750 dsb->state = STATE_PLAYING;
751 maxlen = (len > maxlen) ? len : maxlen;
753 LeaveCriticalSection(&(dsb->lock));
760 static void DSOUND_MixReset(DWORD writepos)
763 IDirectSoundBufferImpl *dsb;
766 TRACE("(%ld)\n", writepos);
768 /* the sound of silence */
769 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
771 /* reset all buffer mix positions */
772 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
773 dsb = dsound->buffers[i];
775 if (!dsb || !dsb->lpVtbl)
777 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
778 TRACE("Resetting %p\n", dsb);
779 EnterCriticalSection(&(dsb->lock));
780 if (dsb->state == STATE_STOPPING) {
781 dsb->state = STATE_STOPPED;
783 else if (dsb->state == STATE_STARTING) {
786 DSOUND_MixCancel(dsb, writepos, FALSE);
787 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
788 dsb->need_remix = FALSE;
790 LeaveCriticalSection(&(dsb->lock));
794 /* wipe out premixed data */
795 if (dsound->mixpos < writepos) {
796 memset(dsound->buffer + writepos, nfiller, dsound->buflen - writepos);
797 memset(dsound->buffer, nfiller, dsound->mixpos);
799 memset(dsound->buffer + writepos, nfiller, dsound->mixpos - writepos);
802 /* reset primary mix position */
803 dsound->mixpos = writepos;
806 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
808 if (dsound->need_remix) {
809 DSOUND_MixReset(writepos);
810 dsound->need_remix = FALSE;
811 /* maximize Half-Life performance */
812 dsound->prebuf = ds_snd_queue_min;
813 dsound->precount = 0;
816 if (dsound->precount >= 4) {
817 if (dsound->prebuf < ds_snd_queue_max)
819 dsound->precount = 0;
822 TRACE("premix adjust: %d\n", dsound->prebuf);
825 void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
827 if (mixq + dsound->pwqueue > ds_hel_queue) mixq = ds_hel_queue - dsound->pwqueue;
828 TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
829 for (; mixq; mixq--) {
830 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
832 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
837 /* #define SYNC_CALLBACK */
839 void DSOUND_PerformMix(void)
847 RtlAcquireResourceShared(&(dsound->lock), TRUE);
849 if (!dsound || !dsound->ref) {
850 /* seems the dsound object is currently being released */
851 RtlReleaseResource(&(dsound->lock));
855 /* the sound of silence */
856 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
858 /* whether the primary is forced to play even without secondary buffers */
859 forced = ((dsound->state == STATE_PLAYING) || (dsound->state == STATE_STARTING));
861 TRACE("entering at %ld\n", GetTickCount());
862 if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
863 BOOL paused = ((dsound->state == STATE_STOPPED) || (dsound->state == STATE_STARTING));
864 /* FIXME: document variables */
865 DWORD playpos, writepos, inq, maxq, frag;
867 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, &writepos);
869 RtlReleaseResource(&(dsound->lock));
872 /* Well, we *could* do Just-In-Time mixing using the writepos,
873 * but that's a little bit ambitious and unnecessary... */
874 /* rather add our safety margin to the writepos, if we're playing */
876 writepos += dsound->writelead;
877 while (writepos >= dsound->buflen)
878 writepos -= dsound->buflen;
879 } else writepos = playpos;
882 playpos = dsound->pwplay * dsound->fraglen;
885 writepos += ds_hel_margin * dsound->fraglen;
886 while (writepos >= dsound->buflen)
887 writepos -= dsound->buflen;
890 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld\n",
891 playpos,writepos,dsound->playpos,dsound->mixpos);
892 /* wipe out just-played sound data */
893 if (playpos < dsound->playpos) {
894 memset(dsound->buffer + dsound->playpos, nfiller, dsound->buflen - dsound->playpos);
895 memset(dsound->buffer, nfiller, playpos);
897 memset(dsound->buffer + dsound->playpos, nfiller, playpos - dsound->playpos);
899 dsound->playpos = playpos;
901 EnterCriticalSection(&(dsound->mixlock));
903 /* reset mixing if necessary */
904 DSOUND_CheckReset(dsound, writepos);
906 /* check how much prebuffering is left */
907 inq = dsound->mixpos;
909 inq += dsound->buflen;
912 /* find the maximum we can prebuffer */
916 maxq += dsound->buflen;
918 } else maxq = dsound->buflen;
920 /* clip maxq to dsound->prebuf */
921 frag = dsound->prebuf * dsound->fraglen;
922 if (maxq > frag) maxq = frag;
924 /* check for consistency */
926 /* the playback position must have passed our last
927 * mixed position, i.e. it's an underrun, or we have
928 * nothing more to play */
929 TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
931 /* stop the playback now, to allow buffers to refill */
932 if (dsound->state == STATE_PLAYING) {
933 dsound->state = STATE_STARTING;
935 else if (dsound->state == STATE_STOPPING) {
936 dsound->state = STATE_STOPPED;
939 /* how can we have an underrun if we aren't playing? */
940 WARN("unexpected primary state (%ld)\n", dsound->state);
943 /* DSOUND_callback may need this lock */
944 LeaveCriticalSection(&(dsound->mixlock));
946 DSOUND_PrimaryStop(dsound);
948 EnterCriticalSection(&(dsound->mixlock));
951 /* the Stop is supposed to reset play position to beginning of buffer */
952 /* unfortunately, OSS is not able to do so, so get current pointer */
953 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, NULL);
955 LeaveCriticalSection(&(dsound->mixlock));
956 RtlReleaseResource(&(dsound->lock));
960 playpos = dsound->pwplay * dsound->fraglen;
963 dsound->playpos = playpos;
964 dsound->mixpos = writepos;
966 maxq = dsound->buflen;
967 if (maxq > frag) maxq = frag;
968 memset(dsound->buffer, nfiller, dsound->buflen);
973 frag = DSOUND_MixToPrimary(playpos, writepos, maxq, paused);
974 if (forced) frag = maxq - inq;
975 dsound->mixpos += frag;
976 while (dsound->mixpos >= dsound->buflen)
977 dsound->mixpos -= dsound->buflen;
980 /* buffers have been filled, restart playback */
981 if (dsound->state == STATE_STARTING) {
982 dsound->state = STATE_PLAYING;
984 else if (dsound->state == STATE_STOPPED) {
985 /* the dsound is supposed to play if there's something to play
986 * even if it is reported as stopped, so don't let this confuse you */
987 dsound->state = STATE_STOPPING;
989 LeaveCriticalSection(&(dsound->mixlock));
991 DSOUND_PrimaryPlay(dsound);
992 TRACE("starting playback\n");
996 LeaveCriticalSection(&(dsound->mixlock));
998 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
999 if (dsound->state == STATE_STARTING) {
1000 DSOUND_PrimaryPlay(dsound);
1001 dsound->state = STATE_PLAYING;
1003 else if (dsound->state == STATE_STOPPING) {
1004 DSOUND_PrimaryStop(dsound);
1005 dsound->state = STATE_STOPPED;
1008 TRACE("completed processing at %ld\n", GetTickCount());
1009 RtlReleaseResource(&(dsound->lock));
1012 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1015 ERR("dsound died without killing us?\n");
1016 timeKillEvent(timerID);
1017 timeEndPeriod(DS_TIME_RES);
1022 DSOUND_PerformMix();
1025 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1027 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1028 TRACE("entering at %ld, msg=%08x(%s)\n", GetTickCount(), msg,
1029 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
1030 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1031 if (msg == MM_WOM_DONE) {
1032 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
1033 if (This->pwqueue == (DWORD)-1) {
1034 TRACE("completed due to reset\n");
1037 /* it could be a bad idea to enter critical section here... if there's lock contention,
1038 * the resulting scheduling delays might obstruct the winmm player thread */
1039 #ifdef SYNC_CALLBACK
1040 EnterCriticalSection(&(This->mixlock));
1042 /* retrieve current values */
1043 fraglen = dsound->fraglen;
1044 buflen = dsound->buflen;
1045 pwplay = dsound->pwplay;
1046 playpos = pwplay * fraglen;
1047 mixpos = dsound->mixpos;
1048 /* check remaining mixed data */
1049 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1050 mixq = inq / fraglen;
1051 if ((inq - (mixq * fraglen)) > 0) mixq++;
1052 /* complete the playing buffer */
1053 TRACE("done playing primary pos=%ld\n", playpos);
1055 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1056 /* write new values */
1057 dsound->pwplay = pwplay;
1059 /* queue new buffer if we have data for it */
1060 if (inq>1) DSOUND_WaveQueue(This, inq-1);
1061 #ifdef SYNC_CALLBACK
1062 LeaveCriticalSection(&(This->mixlock));
1065 TRACE("completed\n");