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
26 #include <sys/types.h>
27 #include <sys/fcntl.h>
33 #include <math.h> /* Insomnia - pow() function */
44 #include "wine/windef16.h"
45 #include "wine/debug.h"
48 #include "dsound_private.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
52 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
55 TRACE("(%p)\n",volpan);
57 TRACE("Vol=%ld Pan=%ld\n", volpan->lVolume, volpan->lPan);
58 /* the AmpFactors are expressed in 16.16 fixed point */
59 volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
60 /* FIXME: dwPan{Left|Right}AmpFactor */
62 /* FIXME: use calculated vol and pan ampfactors */
63 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
64 volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
65 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
66 volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
68 TRACE("left = %lx, right = %lx\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
71 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
74 TRACE("(%p)\n",volpan);
76 TRACE("left=%lx, right=%lx\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
77 if (volpan->dwTotalLeftAmpFactor==0)
80 left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
81 if (volpan->dwTotalRightAmpFactor==0)
84 right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
87 volpan->lVolume=right;
88 volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
93 volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
95 if (volpan->lVolume < -10000)
96 volpan->lVolume=-10000;
97 volpan->lPan=right-left;
98 if (volpan->lPan < -10000)
101 TRACE("Vol=%ld Pan=%ld\n", volpan->lVolume, volpan->lPan);
104 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
109 sw = dsb->pwfx->nChannels * (dsb->pwfx->wBitsPerSample / 8);
110 /* calculate the 10ms write lead */
111 dsb->writelead = (dsb->freq / 100) * sw;
114 void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len)
118 LPDSBPOSITIONNOTIFY event;
119 TRACE("(%p,%d)\n",dsb,len);
121 if (dsb->nrofnotifies == 0)
124 TRACE("(%p) buflen = %ld, playpos = %ld, len = %d\n",
125 dsb, dsb->buflen, dsb->playpos, len);
126 for (i = 0; i < dsb->nrofnotifies ; i++) {
127 event = dsb->notifies + i;
128 offset = event->dwOffset;
129 TRACE("checking %d, position %ld, event = %p\n",
130 i, offset, event->hEventNotify);
131 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
132 /* OK. [Inside DirectX, p274] */
134 /* This also means we can't sort the entries by offset, */
135 /* because DSBPN_OFFSETSTOP == -1 */
136 if (offset == DSBPN_OFFSETSTOP) {
137 if (dsb->state == STATE_STOPPED) {
138 SetEvent(event->hEventNotify);
139 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
144 if ((dsb->playpos + len) >= dsb->buflen) {
145 if ((offset < ((dsb->playpos + len) % dsb->buflen)) ||
146 (offset >= dsb->playpos)) {
147 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
148 SetEvent(event->hEventNotify);
151 if ((offset >= dsb->playpos) && (offset < (dsb->playpos + len))) {
152 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
153 SetEvent(event->hEventNotify);
159 /* WAV format info can be found at:
161 * http://www.cwi.nl/ftp/audio/AudioFormats.part2
162 * ftp://ftp.cwi.nl/pub/audio/RIFF-format
164 * Import points to remember:
165 * 8-bit WAV is unsigned
166 * 16-bit WAV is signed
168 /* Use the same formulas as pcmconverter.c */
169 static inline INT16 cvtU8toS16(BYTE b)
171 return (short)((b+(b << 8))-32768);
174 static inline BYTE cvtS16toU8(INT16 s)
176 return (s >> 8) ^ (unsigned char)0x80;
179 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, BYTE *ibuf, BYTE *obuf )
183 if (dsb->pwfx->wBitsPerSample == 8) {
184 if (dsb->dsound->pwfx->wBitsPerSample == 8 &&
185 dsb->dsound->pwfx->nChannels == dsb->pwfx->nChannels) {
186 /* avoid needless 8->16->8 conversion */
188 if (dsb->pwfx->nChannels==2)
192 fl = cvtU8toS16(*ibuf);
193 fr = (dsb->pwfx->nChannels==2 ? cvtU8toS16(*(ibuf + 1)) : fl);
195 fl = *((INT16 *)ibuf);
196 fr = (dsb->pwfx->nChannels==2 ? *(((INT16 *)ibuf) + 1) : fl);
199 if (dsb->dsound->pwfx->nChannels == 2) {
200 if (dsb->dsound->pwfx->wBitsPerSample == 8) {
201 *obuf = cvtS16toU8(fl);
202 *(obuf + 1) = cvtS16toU8(fr);
205 if (dsb->dsound->pwfx->wBitsPerSample == 16) {
206 *((INT16 *)obuf) = fl;
207 *(((INT16 *)obuf) + 1) = fr;
211 if (dsb->dsound->pwfx->nChannels == 1) {
213 if (dsb->dsound->pwfx->wBitsPerSample == 8) {
214 *obuf = cvtS16toU8(fl);
217 if (dsb->dsound->pwfx->wBitsPerSample == 16) {
218 *((INT16 *)obuf) = fl;
224 /* Now with PerfectPitch (tm) technology */
225 static INT DSOUND_MixerNorm(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
227 INT i, size, ipos, ilen;
229 INT iAdvance = dsb->pwfx->nBlockAlign;
230 INT oAdvance = dsb->dsound->pwfx->nBlockAlign;
232 ibp = dsb->buffer->memory + dsb->buf_mixpos;
235 TRACE("(%p, %p, %p), buf_mixpos=%ld\n", dsb, ibp, obp, dsb->buf_mixpos);
236 /* Check for the best case */
237 if ((dsb->freq == dsb->dsound->pwfx->nSamplesPerSec) &&
238 (dsb->pwfx->wBitsPerSample == dsb->dsound->pwfx->wBitsPerSample) &&
239 (dsb->pwfx->nChannels == dsb->dsound->pwfx->nChannels)) {
240 DWORD bytesleft = dsb->buflen - dsb->buf_mixpos;
241 TRACE("(%p) Best case\n", dsb);
242 if (len <= bytesleft )
243 memcpy(obp, ibp, len);
245 memcpy(obp, ibp, bytesleft );
246 memcpy(obp + bytesleft, dsb->buffer->memory, len - bytesleft);
251 /* Check for same sample rate */
252 if (dsb->freq == dsb->dsound->pwfx->nSamplesPerSec) {
253 TRACE("(%p) Same sample rate %ld = primary %ld\n", dsb,
254 dsb->freq, dsb->dsound->pwfx->nSamplesPerSec);
256 for (i = 0; i < len; i += oAdvance) {
257 cp_fields(dsb, ibp, obp );
261 if (ibp >= (BYTE *)(dsb->buffer->memory + dsb->buflen))
262 ibp = dsb->buffer->memory; /* wrap */
267 /* Mix in different sample rates */
269 /* New PerfectPitch(tm) Technology (c) 1998 Rob Riggs */
270 /* Patent Pending :-] */
272 /* Patent enhancements (c) 2000 Ove KÃ¥ven,
273 * TransGaming Technologies Inc. */
275 /* FIXME("(%p) Adjusting frequency: %ld -> %ld (need optimization)\n",
276 dsb, dsb->freq, dsb->dsound->pwfx->nSamplesPerSec); */
278 size = len / oAdvance;
280 ipos = dsb->buf_mixpos;
281 for (i = 0; i < size; i++) {
282 cp_fields(dsb, (dsb->buffer->memory + ipos), obp);
284 dsb->freqAcc += dsb->freqAdjust;
285 if (dsb->freqAcc >= (1<<DSOUND_FREQSHIFT)) {
286 ULONG adv = (dsb->freqAcc>>DSOUND_FREQSHIFT) * iAdvance;
287 dsb->freqAcc &= (1<<DSOUND_FREQSHIFT)-1;
288 ipos += adv; ilen += adv;
295 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
299 INT16 *bps = (INT16 *) buf;
301 TRACE("(%p,%p,%d)\n",dsb,buf,len);
302 TRACE("left = %lx, right = %lx\n", dsb->cvolpan.dwTotalLeftAmpFactor,
303 dsb->cvolpan.dwTotalRightAmpFactor);
305 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->cvolpan.lPan == 0)) &&
306 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->cvolpan.lVolume == 0)) &&
307 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
308 return; /* Nothing to do */
310 /* If we end up with some bozo coder using panning or 3D sound */
311 /* with a mono primary buffer, it could sound very weird using */
312 /* this method. Oh well, tough patooties. */
314 switch (dsb->dsound->pwfx->wBitsPerSample) {
316 /* 8-bit WAV is unsigned, but we need to operate */
317 /* on signed data for this to work properly */
318 switch (dsb->dsound->pwfx->nChannels) {
320 for (i = 0; i < len; i++) {
321 INT val = *bpc - 128;
322 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
328 for (i = 0; i < len; i+=2) {
329 INT val = *bpc - 128;
330 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
333 val = (val * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
339 FIXME("doesn't support %d channels\n", dsb->dsound->pwfx->nChannels);
344 /* 16-bit WAV is signed -- much better */
345 switch (dsb->dsound->pwfx->nChannels) {
347 for (i = 0; i < len; i += 2) {
348 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
353 for (i = 0; i < len; i += 4) {
354 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
356 *bps = (*bps * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
361 FIXME("doesn't support %d channels\n", dsb->dsound->pwfx->nChannels);
366 FIXME("doesn't support %d bit samples\n", dsb->dsound->pwfx->wBitsPerSample);
371 static LPBYTE DSOUND_tmpbuffer(IDirectSoundImpl *dsound, DWORD len)
373 TRACE("(%p,%ld)\n",dsound,len);
375 if (len > dsound->tmp_buffer_len) {
376 if (dsound->tmp_buffer)
377 dsound->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsound->tmp_buffer, len);
379 dsound->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
381 dsound->tmp_buffer_len = len;
384 return dsound->tmp_buffer;
387 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
389 INT i, len, ilen, temp, field, nBlockAlign, todo;
392 TRACE("(%p,%ld,%ld)\n",dsb,writepos,fraglen);
395 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
396 temp = MulDiv(dsb->dsound->pwfx->nAvgBytesPerSec, dsb->buflen,
397 dsb->nAvgBytesPerSec) -
398 MulDiv(dsb->dsound->pwfx->nAvgBytesPerSec, dsb->buf_mixpos,
399 dsb->nAvgBytesPerSec);
400 len = (len > temp) ? temp : len;
402 nBlockAlign = dsb->dsound->pwfx->nBlockAlign;
403 len = len / nBlockAlign * nBlockAlign; /* data alignment */
406 /* This should only happen if we aren't looping and temp < nBlockAlign */
410 if ((buf = ibuf = DSOUND_tmpbuffer(dsb->dsound, len)) == NULL)
413 TRACE("MixInBuffer (%p) len = %d, 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 (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
419 DSOUND_MixerVol(dsb, ibuf, len);
421 if (dsb->dsound->pwfx->wBitsPerSample == 8) {
422 BYTE *obuf = dsb->dsound->buffer + writepos;
424 if ((writepos + len) <= dsb->dsound->buflen)
427 todo = dsb->dsound->buflen - writepos;
429 for (i = 0; i < todo; i++) {
430 /* 8-bit WAV is unsigned */
431 field = (*ibuf++ - 128);
432 field += (*obuf - 128);
433 if (field > 127) field = 127;
434 else if (field < -128) field = -128;
435 *obuf++ = field + 128;
440 obuf = dsb->dsound->buffer;
442 for (i = 0; i < todo; i++) {
443 /* 8-bit WAV is unsigned */
444 field = (*ibuf++ - 128);
445 field += (*obuf - 128);
446 if (field > 127) field = 127;
447 else if (field < -128) field = -128;
448 *obuf++ = field + 128;
452 INT16 *ibufs, *obufs;
454 ibufs = (INT16 *) ibuf;
455 obufs = (INT16 *)(dsb->dsound->buffer + writepos);
457 if ((writepos + len) <= dsb->dsound->buflen)
460 todo = (dsb->dsound->buflen - writepos) / 2;
462 for (i = 0; i < todo; i++) {
463 /* 16-bit WAV is signed */
466 if (field > 32767) field = 32767;
467 else if (field < -32768) field = -32768;
471 if (todo < (len / 2)) {
472 todo = (len / 2) - todo;
473 obufs = (INT16 *)dsb->dsound->buffer;
475 for (i = 0; i < todo; i++) {
476 /* 16-bit WAV is signed */
479 if (field > 32767) field = 32767;
480 else if (field < -32768) field = -32768;
486 if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
487 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
488 * not the MIX position... but if the sound buffer is bigger than our prebuffering
489 * (which must be the case for the streaming buffers that need this hack anyway)
490 * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
494 dsb->buf_mixpos += ilen;
496 if (dsb->buf_mixpos >= dsb->buflen) {
497 if (dsb->playflags & DSBPLAY_LOOPING) {
499 dsb->buf_mixpos %= dsb->buflen;
500 if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
501 dsb->leadin = FALSE; /* HACK: see above */
508 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
510 INT ilen, field, nBlockAlign;
514 TRACE("(%p,%ld,%ld)\n",dsb,writepos,len);
516 nBlockAlign = dsb->dsound->pwfx->nBlockAlign;
517 len = len / nBlockAlign * nBlockAlign; /* data alignment */
519 if ((buf = ibuf = DSOUND_tmpbuffer(dsb->dsound, len)) == NULL)
522 TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
524 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
525 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
526 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
527 (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
528 DSOUND_MixerVol(dsb, ibuf, len);
530 /* subtract instead of add, to phase out premixed data */
531 if (dsb->dsound->pwfx->wBitsPerSample == 8) {
532 BYTE *obuf = dsb->dsound->buffer + writepos;
534 if ((writepos + len) <= dsb->dsound->buflen)
537 todo = dsb->dsound->buflen - writepos;
539 for (i = 0; i < todo; i++) {
540 /* 8-bit WAV is unsigned */
541 field = (*ibuf++ - 128);
542 field -= (*obuf - 128);
543 if (field > 127) field = 127;
544 else if (field < -128) field = -128;
545 *obuf++ = field + 128;
550 obuf = dsb->dsound->buffer;
552 for (i = 0; i < todo; i++) {
553 /* 8-bit WAV is unsigned */
554 field = (*ibuf++ - 128);
555 field -= (*obuf - 128);
556 if (field > 127) field = 127;
557 else if (field < -128) field = -128;
558 *obuf++ = field + 128;
562 INT16 *ibufs, *obufs;
564 ibufs = (INT16 *) ibuf;
565 obufs = (INT16 *)(dsb->dsound->buffer + writepos);
567 if ((writepos + len) <= dsb->dsound->buflen)
570 todo = (dsb->dsound->buflen - writepos) / 2;
572 for (i = 0; i < todo; i++) {
573 /* 16-bit WAV is signed */
576 if (field > 32767) field = 32767;
577 else if (field < -32768) field = -32768;
581 if (todo < (len / 2)) {
582 todo = (len / 2) - todo;
583 obufs = (INT16 *)dsb->dsound->buffer;
585 for (i = 0; i < todo; i++) {
586 /* 16-bit WAV is signed */
589 if (field > 32767) field = 32767;
590 else if (field < -32768) field = -32768;
597 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
599 DWORD size, flen, len, npos, nlen;
600 INT iAdvance = dsb->pwfx->nBlockAlign;
601 INT oAdvance = dsb->dsound->pwfx->nBlockAlign;
602 /* determine amount of premixed data to cancel */
604 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
605 dsb->primary_mixpos - writepos;
607 TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
609 /* backtrack the mix position */
610 size = primary_done / oAdvance;
611 flen = size * dsb->freqAdjust;
612 len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
613 flen &= (1<<DSOUND_FREQSHIFT)-1;
614 while (dsb->freqAcc < flen) {
616 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
619 npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
620 dsb->buf_mixpos - len;
621 if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
622 /* stop backtracking at startpos */
623 npos = dsb->startpos;
624 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
625 dsb->buf_mixpos - npos;
627 nlen = len / dsb->pwfx->nBlockAlign;
628 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
629 nlen *= dsb->dsound->pwfx->nBlockAlign;
631 ((dsb->primary_mixpos < nlen) ? dsb->dsound->buflen : 0) +
632 dsb->primary_mixpos - nlen;
635 dsb->freqAcc -= flen;
636 dsb->buf_mixpos = npos;
637 dsb->primary_mixpos = writepos;
639 TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
640 dsb->buf_mixpos, dsb->primary_mixpos, len);
642 if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
645 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
648 DWORD i, size, flen, len, npos, nlen;
649 INT iAdvance = dsb->pwfx->nBlockAlign;
650 INT oAdvance = dsb->dsound->pwfx->nBlockAlign;
651 /* determine amount of premixed data to cancel */
653 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
654 dsb->buf_mixpos - buf_writepos;
657 WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
658 /* since this is not implemented yet, just cancel *ALL* prebuffering for now
659 * (which is faster anyway when there's only a single secondary buffer) */
660 dsb->dsound->need_remix = TRUE;
663 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
666 EnterCriticalSection(&dsb->lock);
667 if (dsb->state == STATE_PLAYING) {
668 #if 0 /* this may not be quite reliable yet */
669 dsb->need_remix = TRUE;
671 dsb->dsound->need_remix = TRUE;
674 LeaveCriticalSection(&dsb->lock);
677 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
680 /* determine this buffer's write position */
681 DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, dsb->state & dsb->dsound->state, writepos,
682 writepos, dsb->primary_mixpos, dsb->buf_mixpos);
683 /* determine how much already-mixed data exists */
685 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
686 dsb->buf_mixpos - buf_writepos;
688 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
689 dsb->primary_mixpos - writepos;
691 ((dsb->dsound->mixpos < writepos) ? dsb->dsound->buflen : 0) +
692 dsb->dsound->mixpos - writepos;
694 ((buf_writepos < dsb->playpos) ? dsb->buflen : 0) +
695 buf_writepos - dsb->playpos;
696 DWORD buf_left = dsb->buflen - buf_writepos;
699 TRACE("(%p,%ld,%ld,%ld)\n",dsb,playpos,writepos,mixlen);
700 TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
701 TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
702 TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
704 TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
706 /* check for notification positions */
707 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
708 dsb->state != STATE_STARTING) {
709 DSOUND_CheckEvent(dsb, played);
712 /* save write position for non-GETCURRENTPOSITION2... */
713 dsb->playpos = buf_writepos;
715 /* check whether CalcPlayPosition detected a mixing underrun */
716 if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
717 /* it did, but did we have more to play? */
718 if ((dsb->playflags & DSBPLAY_LOOPING) ||
719 (dsb->buf_mixpos < dsb->buflen)) {
720 /* yes, have to recover */
721 ERR("underrun on sound buffer %p\n", dsb);
722 TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
724 dsb->primary_mixpos = writepos;
727 /* determine how far ahead we should mix */
728 if (((dsb->playflags & DSBPLAY_LOOPING) ||
729 (dsb->leadin && (dsb->probably_valid_to != 0))) &&
730 !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
731 /* if this is a streaming buffer, it typically means that
732 * we should defer mixing past probably_valid_to as long
733 * as we can, to avoid unnecessary remixing */
734 /* the heavy-looking calculations shouldn't be that bad,
735 * as any game isn't likely to be have more than 1 or 2
736 * streaming buffers in use at any time anyway... */
737 DWORD probably_valid_left =
738 (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
739 ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
740 dsb->probably_valid_to - buf_writepos;
741 /* check for leadin condition */
742 if ((probably_valid_left == 0) &&
743 (dsb->probably_valid_to == dsb->startpos) &&
745 probably_valid_left = dsb->buflen;
746 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
747 dsb->probably_valid_to, probably_valid_left);
748 /* check whether the app's time is already up */
749 if (probably_valid_left < dsb->writelead) {
750 WARN("probably_valid_to now within writelead, possible streaming underrun\n");
751 /* once we pass the point of no return,
752 * no reason to hold back anymore */
753 dsb->probably_valid_to = (DWORD)-1;
754 /* we just have to go ahead and mix what we have,
755 * there's no telling what the app is thinking anyway */
757 /* adjust for our frequency and our sample size */
758 probably_valid_left = MulDiv(probably_valid_left,
759 1 << DSOUND_FREQSHIFT,
760 dsb->pwfx->nBlockAlign * dsb->freqAdjust) *
761 dsb->dsound->pwfx->nBlockAlign;
762 /* check whether to clip mix_len */
763 if (probably_valid_left < mixlen) {
764 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
765 mixlen = probably_valid_left;
769 /* cut mixlen with what's already been mixed */
770 if (mixlen < primary_done) {
771 /* huh? and still CalcPlayPosition didn't
772 * detect an underrun? */
773 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
776 len = mixlen - primary_done;
777 TRACE("remaining mixlen=%ld\n", len);
779 if (len < dsb->dsound->fraglen) {
780 /* smaller than a fragment, wait until it gets larger
781 * before we take the mixing overhead */
782 TRACE("mixlen not worth it, deferring mixing\n");
787 /* ok, we know how much to mix, let's go */
788 still_behind = (adv_done > primary_done);
790 slen = dsb->dsound->buflen - dsb->primary_mixpos;
791 if (slen > len) slen = len;
792 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
794 if ((dsb->primary_mixpos < dsb->dsound->mixpos) &&
795 (dsb->primary_mixpos + slen >= dsb->dsound->mixpos))
796 still_behind = FALSE;
798 dsb->primary_mixpos += slen; len -= slen;
799 dsb->primary_mixpos %= dsb->dsound->buflen;
801 if ((dsb->state == STATE_STOPPED) || !slen) break;
803 TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->mixpos);
804 TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
807 /* check if buffer should be considered complete */
808 if (buf_left < dsb->writelead &&
809 !(dsb->playflags & DSBPLAY_LOOPING)) {
810 dsb->state = STATE_STOPPED;
812 dsb->last_playpos = 0;
815 DSOUND_CheckEvent(dsb, buf_left);
818 /* return how far we think the primary buffer can
819 * advance its underrun detector...*/
820 if (still_behind) return 0;
821 if ((mixlen - len) < primary_done) return 0;
822 slen = ((dsb->primary_mixpos < dsb->dsound->mixpos) ?
823 dsb->dsound->buflen : 0) + dsb->primary_mixpos -
826 /* the primary_done and still_behind checks above should have worked */
827 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
833 static DWORD DSOUND_MixToPrimary(IDirectSoundImpl *dsound, DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
835 INT i, len, maxlen = 0;
836 IDirectSoundBufferImpl *dsb;
838 TRACE("(%ld,%ld,%ld,%d)\n", playpos, writepos, mixlen, recover);
839 for (i = 0; i < dsound->nrofbuffers; i++) {
840 dsb = dsound->buffers[i];
842 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
843 TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
844 EnterCriticalSection(&(dsb->lock));
845 if (dsb->state == STATE_STOPPING) {
846 DSOUND_MixCancel(dsb, writepos, TRUE);
847 dsb->state = STATE_STOPPED;
848 DSOUND_CheckEvent(dsb, 0);
850 if ((dsb->state == STATE_STARTING) || recover) {
851 dsb->primary_mixpos = writepos;
852 dsb->cvolpan = dsb->volpan;
853 dsb->need_remix = FALSE;
855 else if (dsb->need_remix) {
856 DSOUND_MixCancel(dsb, writepos, TRUE);
857 dsb->cvolpan = dsb->volpan;
858 dsb->need_remix = FALSE;
860 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
861 if (dsb->state == STATE_STARTING)
862 dsb->state = STATE_PLAYING;
863 maxlen = (len > maxlen) ? len : maxlen;
865 LeaveCriticalSection(&(dsb->lock));
872 static void DSOUND_MixReset(IDirectSoundImpl *dsound, DWORD writepos)
875 IDirectSoundBufferImpl *dsb;
878 TRACE("(%ld)\n", writepos);
880 /* the sound of silence */
881 nfiller = dsound->pwfx->wBitsPerSample == 8 ? 128 : 0;
883 /* reset all buffer mix positions */
884 for (i = 0; i < dsound->nrofbuffers; i++) {
885 dsb = dsound->buffers[i];
887 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
888 TRACE("Resetting %p\n", dsb);
889 EnterCriticalSection(&(dsb->lock));
890 if (dsb->state == STATE_STOPPING) {
891 dsb->state = STATE_STOPPED;
893 else if (dsb->state == STATE_STARTING) {
896 DSOUND_MixCancel(dsb, writepos, FALSE);
897 dsb->cvolpan = dsb->volpan;
898 dsb->need_remix = FALSE;
900 LeaveCriticalSection(&(dsb->lock));
904 /* wipe out premixed data */
905 if (dsound->mixpos < writepos) {
906 memset(dsound->buffer + writepos, nfiller, dsound->buflen - writepos);
907 memset(dsound->buffer, nfiller, dsound->mixpos);
909 memset(dsound->buffer + writepos, nfiller, dsound->mixpos - writepos);
912 /* reset primary mix position */
913 dsound->mixpos = writepos;
916 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
918 TRACE("(%p,%ld)\n",dsound,writepos);
919 if (dsound->need_remix) {
920 DSOUND_MixReset(dsound, writepos);
921 dsound->need_remix = FALSE;
922 /* maximize Half-Life performance */
923 dsound->prebuf = ds_snd_queue_min;
924 dsound->precount = 0;
927 if (dsound->precount >= 4) {
928 if (dsound->prebuf < ds_snd_queue_max)
930 dsound->precount = 0;
933 TRACE("premix adjust: %d\n", dsound->prebuf);
936 void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
938 TRACE("(%p,%ld)\n",dsound,mixq);
939 if (mixq + dsound->pwqueue > ds_hel_queue) mixq = ds_hel_queue - dsound->pwqueue;
940 TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
941 for (; mixq; mixq--) {
942 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
944 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
949 /* #define SYNC_CALLBACK */
951 void DSOUND_PerformMix(IDirectSoundImpl *dsound)
957 TRACE("(%p)\n", dsound);
959 /* the sound of silence */
960 nfiller = dsound->pwfx->wBitsPerSample == 8 ? 128 : 0;
962 /* whether the primary is forced to play even without secondary buffers */
963 forced = ((dsound->state == STATE_PLAYING) || (dsound->state == STATE_STARTING));
965 if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
966 BOOL paused = ((dsound->state == STATE_STOPPED) || (dsound->state == STATE_STARTING));
967 /* FIXME: document variables */
968 DWORD playpos, writepos, inq, maxq, frag;
970 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, &writepos);
972 WARN("IDsDriverBuffer_GetPosition failed\n");
975 /* Well, we *could* do Just-In-Time mixing using the writepos,
976 * but that's a little bit ambitious and unnecessary... */
977 /* rather add our safety margin to the writepos, if we're playing */
979 writepos += dsound->writelead;
980 writepos %= dsound->buflen;
981 } else writepos = playpos;
983 playpos = dsound->pwplay * dsound->fraglen;
986 writepos += ds_hel_margin * dsound->fraglen;
987 writepos %= dsound->buflen;
990 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld, buflen=%ld\n",
991 playpos,writepos,dsound->playpos,dsound->mixpos,dsound->buflen);
992 assert(dsound->playpos < dsound->buflen);
993 /* wipe out just-played sound data */
994 if (playpos < dsound->playpos) {
995 memset(dsound->buffer + dsound->playpos, nfiller, dsound->buflen - dsound->playpos);
996 memset(dsound->buffer, nfiller, playpos);
998 memset(dsound->buffer + dsound->playpos, nfiller, playpos - dsound->playpos);
1000 dsound->playpos = playpos;
1002 EnterCriticalSection(&(dsound->mixlock));
1004 /* reset mixing if necessary */
1005 DSOUND_CheckReset(dsound, writepos);
1007 /* check how much prebuffering is left */
1008 inq = dsound->mixpos;
1010 inq += dsound->buflen;
1013 /* find the maximum we can prebuffer */
1016 if (maxq < writepos)
1017 maxq += dsound->buflen;
1019 } else maxq = dsound->buflen;
1021 /* clip maxq to dsound->prebuf */
1022 frag = dsound->prebuf * dsound->fraglen;
1023 if (maxq > frag) maxq = frag;
1025 /* check for consistency */
1027 /* the playback position must have passed our last
1028 * mixed position, i.e. it's an underrun, or we have
1029 * nothing more to play */
1030 TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
1032 /* stop the playback now, to allow buffers to refill */
1033 if (dsound->state == STATE_PLAYING) {
1034 dsound->state = STATE_STARTING;
1036 else if (dsound->state == STATE_STOPPING) {
1037 dsound->state = STATE_STOPPED;
1040 /* how can we have an underrun if we aren't playing? */
1041 WARN("unexpected primary state (%ld)\n", dsound->state);
1043 #ifdef SYNC_CALLBACK
1044 /* DSOUND_callback may need this lock */
1045 LeaveCriticalSection(&(dsound->mixlock));
1047 if (DSOUND_PrimaryStop(dsound) != DS_OK)
1048 WARN("DSOUND_PrimaryStop failed\n");
1049 #ifdef SYNC_CALLBACK
1050 EnterCriticalSection(&(dsound->mixlock));
1052 if (dsound->hwbuf) {
1053 /* the Stop is supposed to reset play position to beginning of buffer */
1054 /* unfortunately, OSS is not able to do so, so get current pointer */
1055 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, NULL);
1057 LeaveCriticalSection(&(dsound->mixlock));
1058 WARN("IDsDriverBuffer_GetPosition failed\n");
1062 playpos = dsound->pwplay * dsound->fraglen;
1065 dsound->playpos = playpos;
1066 dsound->mixpos = writepos;
1068 maxq = dsound->buflen;
1069 if (maxq > frag) maxq = frag;
1070 memset(dsound->buffer, nfiller, dsound->buflen);
1075 frag = DSOUND_MixToPrimary(dsound, playpos, writepos, maxq, paused);
1076 if (forced) frag = maxq - inq;
1077 dsound->mixpos += frag;
1078 dsound->mixpos %= dsound->buflen;
1081 /* buffers have been filled, restart playback */
1082 if (dsound->state == STATE_STARTING) {
1083 dsound->state = STATE_PLAYING;
1085 else if (dsound->state == STATE_STOPPED) {
1086 /* the dsound is supposed to play if there's something to play
1087 * even if it is reported as stopped, so don't let this confuse you */
1088 dsound->state = STATE_STOPPING;
1090 LeaveCriticalSection(&(dsound->mixlock));
1092 if (DSOUND_PrimaryPlay(dsound) != DS_OK)
1093 WARN("DSOUND_PrimaryPlay failed\n");
1095 TRACE("starting playback\n");
1099 LeaveCriticalSection(&(dsound->mixlock));
1101 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
1102 if (dsound->state == STATE_STARTING) {
1103 if (DSOUND_PrimaryPlay(dsound) != DS_OK)
1104 WARN("DSOUND_PrimaryPlay failed\n");
1106 dsound->state = STATE_PLAYING;
1108 else if (dsound->state == STATE_STOPPING) {
1109 if (DSOUND_PrimaryStop(dsound) != DS_OK)
1110 WARN("DSOUND_PrimaryStop failed\n");
1112 dsound->state = STATE_STOPPED;
1117 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1119 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1120 DWORD start_time = GetTickCount();
1122 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
1123 TRACE("entering at %ld\n", start_time);
1125 if (dsound != This) {
1126 ERR("dsound died without killing us?\n");
1127 timeKillEvent(timerID);
1128 timeEndPeriod(DS_TIME_RES);
1132 RtlAcquireResourceShared(&(This->buffer_list_lock), TRUE);
1135 DSOUND_PerformMix(This);
1137 RtlReleaseResource(&(This->buffer_list_lock));
1139 end_time = GetTickCount();
1140 TRACE("completed processing at %ld, duration = %ld\n", end_time, end_time - start_time);
1143 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1145 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1146 TRACE("(%p,%x,%lx,%lx,%lx)\n",hwo,msg,dwUser,dw1,dw2);
1147 TRACE("entering at %ld, msg=%08x(%s)\n", GetTickCount(), msg,
1148 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
1149 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1150 if (msg == MM_WOM_DONE) {
1151 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
1152 if (This->pwqueue == (DWORD)-1) {
1153 TRACE("completed due to reset\n");
1156 /* it could be a bad idea to enter critical section here... if there's lock contention,
1157 * the resulting scheduling delays might obstruct the winmm player thread */
1158 #ifdef SYNC_CALLBACK
1159 EnterCriticalSection(&(This->mixlock));
1161 /* retrieve current values */
1162 fraglen = This->fraglen;
1163 buflen = This->buflen;
1164 pwplay = This->pwplay;
1165 playpos = pwplay * fraglen;
1166 mixpos = This->mixpos;
1167 /* check remaining mixed data */
1168 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1169 mixq = inq / fraglen;
1170 if ((inq - (mixq * fraglen)) > 0) mixq++;
1171 /* complete the playing buffer */
1172 TRACE("done playing primary pos=%ld\n", playpos);
1174 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1175 /* write new values */
1176 This->pwplay = pwplay;
1178 /* queue new buffer if we have data for it */
1179 if (inq>1) DSOUND_WaveQueue(This, inq-1);
1180 #ifdef SYNC_CALLBACK
1181 LeaveCriticalSection(&(This->mixlock));
1184 TRACE("completed\n");