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 void *tmp_buffer;
372 static size_t tmp_buffer_len = 0;
374 static void *DSOUND_tmpbuffer(size_t len)
376 if (len>tmp_buffer_len) {
377 void *new_buffer = realloc(tmp_buffer, len);
379 tmp_buffer = new_buffer;
380 tmp_buffer_len = len;
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 /* Been seeing segfaults in malloc() for some reason... */
411 TRACE("allocating buffer (size = %d)\n", len);
412 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
415 TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
417 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
418 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
419 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
420 (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
421 DSOUND_MixerVol(dsb, ibuf, len);
423 if (dsb->dsound->pwfx->wBitsPerSample == 8) {
424 BYTE *obuf = dsb->dsound->buffer + writepos;
426 if ((writepos + len) <= dsb->dsound->buflen)
429 todo = dsb->dsound->buflen - writepos;
431 for (i = 0; i < todo; i++) {
432 /* 8-bit WAV is unsigned */
433 field = (*ibuf++ - 128);
434 field += (*obuf - 128);
435 if (field > 127) field = 127;
436 else if (field < -128) field = -128;
437 *obuf++ = field + 128;
442 obuf = dsb->dsound->buffer;
444 for (i = 0; i < todo; i++) {
445 /* 8-bit WAV is unsigned */
446 field = (*ibuf++ - 128);
447 field += (*obuf - 128);
448 if (field > 127) field = 127;
449 else if (field < -128) field = -128;
450 *obuf++ = field + 128;
454 INT16 *ibufs, *obufs;
456 ibufs = (INT16 *) ibuf;
457 obufs = (INT16 *)(dsb->dsound->buffer + writepos);
459 if ((writepos + len) <= dsb->dsound->buflen)
462 todo = (dsb->dsound->buflen - writepos) / 2;
464 for (i = 0; i < todo; i++) {
465 /* 16-bit WAV is signed */
468 if (field > 32767) field = 32767;
469 else if (field < -32768) field = -32768;
473 if (todo < (len / 2)) {
474 todo = (len / 2) - todo;
475 obufs = (INT16 *)dsb->dsound->buffer;
477 for (i = 0; i < todo; i++) {
478 /* 16-bit WAV is signed */
481 if (field > 32767) field = 32767;
482 else if (field < -32768) field = -32768;
488 if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
489 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
490 * not the MIX position... but if the sound buffer is bigger than our prebuffering
491 * (which must be the case for the streaming buffers that need this hack anyway)
492 * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
496 dsb->buf_mixpos += ilen;
498 if (dsb->buf_mixpos >= dsb->buflen) {
499 if (dsb->playflags & DSBPLAY_LOOPING) {
501 dsb->buf_mixpos %= dsb->buflen;
502 if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
503 dsb->leadin = FALSE; /* HACK: see above */
510 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
512 INT ilen, field, nBlockAlign;
516 TRACE("(%p,%ld,%ld)\n",dsb,writepos,len);
518 nBlockAlign = dsb->dsound->pwfx->nBlockAlign;
519 len = len / nBlockAlign * nBlockAlign; /* data alignment */
521 TRACE("allocating buffer (size = %ld)\n", len);
522 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
525 TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
527 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
528 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
529 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
530 (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
531 DSOUND_MixerVol(dsb, ibuf, len);
533 /* subtract instead of add, to phase out premixed data */
534 if (dsb->dsound->pwfx->wBitsPerSample == 8) {
535 BYTE *obuf = dsb->dsound->buffer + writepos;
537 if ((writepos + len) <= dsb->dsound->buflen)
540 todo = dsb->dsound->buflen - writepos;
542 for (i = 0; i < todo; i++) {
543 /* 8-bit WAV is unsigned */
544 field = (*ibuf++ - 128);
545 field -= (*obuf - 128);
546 if (field > 127) field = 127;
547 else if (field < -128) field = -128;
548 *obuf++ = field + 128;
553 obuf = dsb->dsound->buffer;
555 for (i = 0; i < todo; i++) {
556 /* 8-bit WAV is unsigned */
557 field = (*ibuf++ - 128);
558 field -= (*obuf - 128);
559 if (field > 127) field = 127;
560 else if (field < -128) field = -128;
561 *obuf++ = field + 128;
565 INT16 *ibufs, *obufs;
567 ibufs = (INT16 *) ibuf;
568 obufs = (INT16 *)(dsb->dsound->buffer + writepos);
570 if ((writepos + len) <= dsb->dsound->buflen)
573 todo = (dsb->dsound->buflen - writepos) / 2;
575 for (i = 0; i < todo; i++) {
576 /* 16-bit WAV is signed */
579 if (field > 32767) field = 32767;
580 else if (field < -32768) field = -32768;
584 if (todo < (len / 2)) {
585 todo = (len / 2) - todo;
586 obufs = (INT16 *)dsb->dsound->buffer;
588 for (i = 0; i < todo; i++) {
589 /* 16-bit WAV is signed */
592 if (field > 32767) field = 32767;
593 else if (field < -32768) field = -32768;
600 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
602 DWORD size, flen, len, npos, nlen;
603 INT iAdvance = dsb->pwfx->nBlockAlign;
604 INT oAdvance = dsb->dsound->pwfx->nBlockAlign;
605 /* determine amount of premixed data to cancel */
607 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
608 dsb->primary_mixpos - writepos;
610 TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
612 /* backtrack the mix position */
613 size = primary_done / oAdvance;
614 flen = size * dsb->freqAdjust;
615 len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
616 flen &= (1<<DSOUND_FREQSHIFT)-1;
617 while (dsb->freqAcc < flen) {
619 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
622 npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
623 dsb->buf_mixpos - len;
624 if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
625 /* stop backtracking at startpos */
626 npos = dsb->startpos;
627 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
628 dsb->buf_mixpos - npos;
630 nlen = len / dsb->pwfx->nBlockAlign;
631 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
632 nlen *= dsb->dsound->pwfx->nBlockAlign;
634 ((dsb->primary_mixpos < nlen) ? dsb->dsound->buflen : 0) +
635 dsb->primary_mixpos - nlen;
638 dsb->freqAcc -= flen;
639 dsb->buf_mixpos = npos;
640 dsb->primary_mixpos = writepos;
642 TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
643 dsb->buf_mixpos, dsb->primary_mixpos, len);
645 if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
648 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
651 DWORD i, size, flen, len, npos, nlen;
652 INT iAdvance = dsb->pwfx->nBlockAlign;
653 INT oAdvance = dsb->dsound->pwfx->nBlockAlign;
654 /* determine amount of premixed data to cancel */
656 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
657 dsb->buf_mixpos - buf_writepos;
660 WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
661 /* since this is not implemented yet, just cancel *ALL* prebuffering for now
662 * (which is faster anyway when there's only a single secondary buffer) */
663 dsb->dsound->need_remix = TRUE;
666 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
669 EnterCriticalSection(&dsb->lock);
670 if (dsb->state == STATE_PLAYING) {
671 #if 0 /* this may not be quite reliable yet */
672 dsb->need_remix = TRUE;
674 dsb->dsound->need_remix = TRUE;
677 LeaveCriticalSection(&dsb->lock);
680 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
683 /* determine this buffer's write position */
684 DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, dsb->state & dsb->dsound->state, writepos,
685 writepos, dsb->primary_mixpos, dsb->buf_mixpos);
686 /* determine how much already-mixed data exists */
688 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
689 dsb->buf_mixpos - buf_writepos;
691 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
692 dsb->primary_mixpos - writepos;
694 ((dsb->dsound->mixpos < writepos) ? dsb->dsound->buflen : 0) +
695 dsb->dsound->mixpos - writepos;
697 ((buf_writepos < dsb->playpos) ? dsb->buflen : 0) +
698 buf_writepos - dsb->playpos;
699 DWORD buf_left = dsb->buflen - buf_writepos;
702 TRACE("(%p,%ld,%ld,%ld)\n",dsb,playpos,writepos,mixlen);
703 TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
704 TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
705 TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
707 TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
709 /* check for notification positions */
710 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
711 dsb->state != STATE_STARTING) {
712 DSOUND_CheckEvent(dsb, played);
715 /* save write position for non-GETCURRENTPOSITION2... */
716 dsb->playpos = buf_writepos;
718 /* check whether CalcPlayPosition detected a mixing underrun */
719 if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
720 /* it did, but did we have more to play? */
721 if ((dsb->playflags & DSBPLAY_LOOPING) ||
722 (dsb->buf_mixpos < dsb->buflen)) {
723 /* yes, have to recover */
724 ERR("underrun on sound buffer %p\n", dsb);
725 TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
727 dsb->primary_mixpos = writepos;
730 /* determine how far ahead we should mix */
731 if (((dsb->playflags & DSBPLAY_LOOPING) ||
732 (dsb->leadin && (dsb->probably_valid_to != 0))) &&
733 !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
734 /* if this is a streaming buffer, it typically means that
735 * we should defer mixing past probably_valid_to as long
736 * as we can, to avoid unnecessary remixing */
737 /* the heavy-looking calculations shouldn't be that bad,
738 * as any game isn't likely to be have more than 1 or 2
739 * streaming buffers in use at any time anyway... */
740 DWORD probably_valid_left =
741 (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
742 ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
743 dsb->probably_valid_to - buf_writepos;
744 /* check for leadin condition */
745 if ((probably_valid_left == 0) &&
746 (dsb->probably_valid_to == dsb->startpos) &&
748 probably_valid_left = dsb->buflen;
749 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
750 dsb->probably_valid_to, probably_valid_left);
751 /* check whether the app's time is already up */
752 if (probably_valid_left < dsb->writelead) {
753 WARN("probably_valid_to now within writelead, possible streaming underrun\n");
754 /* once we pass the point of no return,
755 * no reason to hold back anymore */
756 dsb->probably_valid_to = (DWORD)-1;
757 /* we just have to go ahead and mix what we have,
758 * there's no telling what the app is thinking anyway */
760 /* adjust for our frequency and our sample size */
761 probably_valid_left = MulDiv(probably_valid_left,
762 1 << DSOUND_FREQSHIFT,
763 dsb->pwfx->nBlockAlign * dsb->freqAdjust) *
764 dsb->dsound->pwfx->nBlockAlign;
765 /* check whether to clip mix_len */
766 if (probably_valid_left < mixlen) {
767 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
768 mixlen = probably_valid_left;
772 /* cut mixlen with what's already been mixed */
773 if (mixlen < primary_done) {
774 /* huh? and still CalcPlayPosition didn't
775 * detect an underrun? */
776 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
779 len = mixlen - primary_done;
780 TRACE("remaining mixlen=%ld\n", len);
782 if (len < dsb->dsound->fraglen) {
783 /* smaller than a fragment, wait until it gets larger
784 * before we take the mixing overhead */
785 TRACE("mixlen not worth it, deferring mixing\n");
790 /* ok, we know how much to mix, let's go */
791 still_behind = (adv_done > primary_done);
793 slen = dsb->dsound->buflen - dsb->primary_mixpos;
794 if (slen > len) slen = len;
795 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
797 if ((dsb->primary_mixpos < dsb->dsound->mixpos) &&
798 (dsb->primary_mixpos + slen >= dsb->dsound->mixpos))
799 still_behind = FALSE;
801 dsb->primary_mixpos += slen; len -= slen;
802 dsb->primary_mixpos %= dsb->dsound->buflen;
804 if ((dsb->state == STATE_STOPPED) || !slen) break;
806 TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->mixpos);
807 TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
810 /* check if buffer should be considered complete */
811 if (buf_left < dsb->writelead &&
812 !(dsb->playflags & DSBPLAY_LOOPING)) {
813 dsb->state = STATE_STOPPED;
815 dsb->last_playpos = 0;
818 DSOUND_CheckEvent(dsb, buf_left);
821 /* return how far we think the primary buffer can
822 * advance its underrun detector...*/
823 if (still_behind) return 0;
824 if ((mixlen - len) < primary_done) return 0;
825 slen = ((dsb->primary_mixpos < dsb->dsound->mixpos) ?
826 dsb->dsound->buflen : 0) + dsb->primary_mixpos -
829 /* the primary_done and still_behind checks above should have worked */
830 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
836 static DWORD DSOUND_MixToPrimary(IDirectSoundImpl *dsound, DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
838 INT i, len, maxlen = 0;
839 IDirectSoundBufferImpl *dsb;
841 TRACE("(%ld,%ld,%ld,%d)\n", playpos, writepos, mixlen, recover);
842 for (i = 0; i < dsound->nrofbuffers; i++) {
843 dsb = dsound->buffers[i];
845 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
846 TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
847 EnterCriticalSection(&(dsb->lock));
848 if (dsb->state == STATE_STOPPING) {
849 DSOUND_MixCancel(dsb, writepos, TRUE);
850 dsb->state = STATE_STOPPED;
851 DSOUND_CheckEvent(dsb, 0);
853 if ((dsb->state == STATE_STARTING) || recover) {
854 dsb->primary_mixpos = writepos;
855 dsb->cvolpan = dsb->volpan;
856 dsb->need_remix = FALSE;
858 else if (dsb->need_remix) {
859 DSOUND_MixCancel(dsb, writepos, TRUE);
860 dsb->cvolpan = dsb->volpan;
861 dsb->need_remix = FALSE;
863 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
864 if (dsb->state == STATE_STARTING)
865 dsb->state = STATE_PLAYING;
866 maxlen = (len > maxlen) ? len : maxlen;
868 LeaveCriticalSection(&(dsb->lock));
875 static void DSOUND_MixReset(IDirectSoundImpl *dsound, DWORD writepos)
878 IDirectSoundBufferImpl *dsb;
881 TRACE("(%ld)\n", writepos);
883 /* the sound of silence */
884 nfiller = dsound->pwfx->wBitsPerSample == 8 ? 128 : 0;
886 /* reset all buffer mix positions */
887 for (i = 0; i < dsound->nrofbuffers; i++) {
888 dsb = dsound->buffers[i];
890 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
891 TRACE("Resetting %p\n", dsb);
892 EnterCriticalSection(&(dsb->lock));
893 if (dsb->state == STATE_STOPPING) {
894 dsb->state = STATE_STOPPED;
896 else if (dsb->state == STATE_STARTING) {
899 DSOUND_MixCancel(dsb, writepos, FALSE);
900 dsb->cvolpan = dsb->volpan;
901 dsb->need_remix = FALSE;
903 LeaveCriticalSection(&(dsb->lock));
907 /* wipe out premixed data */
908 if (dsound->mixpos < writepos) {
909 memset(dsound->buffer + writepos, nfiller, dsound->buflen - writepos);
910 memset(dsound->buffer, nfiller, dsound->mixpos);
912 memset(dsound->buffer + writepos, nfiller, dsound->mixpos - writepos);
915 /* reset primary mix position */
916 dsound->mixpos = writepos;
919 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
921 TRACE("(%p,%ld)\n",dsound,writepos);
922 if (dsound->need_remix) {
923 DSOUND_MixReset(dsound, writepos);
924 dsound->need_remix = FALSE;
925 /* maximize Half-Life performance */
926 dsound->prebuf = ds_snd_queue_min;
927 dsound->precount = 0;
930 if (dsound->precount >= 4) {
931 if (dsound->prebuf < ds_snd_queue_max)
933 dsound->precount = 0;
936 TRACE("premix adjust: %d\n", dsound->prebuf);
939 void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
941 TRACE("(%p,%ld)\n",dsound,mixq);
942 if (mixq + dsound->pwqueue > ds_hel_queue) mixq = ds_hel_queue - dsound->pwqueue;
943 TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
944 for (; mixq; mixq--) {
945 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
947 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
952 /* #define SYNC_CALLBACK */
954 void DSOUND_PerformMix(IDirectSoundImpl *dsound)
960 TRACE("(%p)\n", dsound);
962 /* the sound of silence */
963 nfiller = dsound->pwfx->wBitsPerSample == 8 ? 128 : 0;
965 /* whether the primary is forced to play even without secondary buffers */
966 forced = ((dsound->state == STATE_PLAYING) || (dsound->state == STATE_STARTING));
968 if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
969 BOOL paused = ((dsound->state == STATE_STOPPED) || (dsound->state == STATE_STARTING));
970 /* FIXME: document variables */
971 DWORD playpos, writepos, inq, maxq, frag;
973 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, &writepos);
975 WARN("IDsDriverBuffer_GetPosition failed\n");
978 /* Well, we *could* do Just-In-Time mixing using the writepos,
979 * but that's a little bit ambitious and unnecessary... */
980 /* rather add our safety margin to the writepos, if we're playing */
982 writepos += dsound->writelead;
983 writepos %= dsound->buflen;
984 } else writepos = playpos;
986 playpos = dsound->pwplay * dsound->fraglen;
989 writepos += ds_hel_margin * dsound->fraglen;
990 writepos %= dsound->buflen;
993 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld, buflen=%ld\n",
994 playpos,writepos,dsound->playpos,dsound->mixpos,dsound->buflen);
995 assert(dsound->playpos < dsound->buflen);
996 /* wipe out just-played sound data */
997 if (playpos < dsound->playpos) {
998 memset(dsound->buffer + dsound->playpos, nfiller, dsound->buflen - dsound->playpos);
999 memset(dsound->buffer, nfiller, playpos);
1001 memset(dsound->buffer + dsound->playpos, nfiller, playpos - dsound->playpos);
1003 dsound->playpos = playpos;
1005 EnterCriticalSection(&(dsound->mixlock));
1007 /* reset mixing if necessary */
1008 DSOUND_CheckReset(dsound, writepos);
1010 /* check how much prebuffering is left */
1011 inq = dsound->mixpos;
1013 inq += dsound->buflen;
1016 /* find the maximum we can prebuffer */
1019 if (maxq < writepos)
1020 maxq += dsound->buflen;
1022 } else maxq = dsound->buflen;
1024 /* clip maxq to dsound->prebuf */
1025 frag = dsound->prebuf * dsound->fraglen;
1026 if (maxq > frag) maxq = frag;
1028 /* check for consistency */
1030 /* the playback position must have passed our last
1031 * mixed position, i.e. it's an underrun, or we have
1032 * nothing more to play */
1033 TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
1035 /* stop the playback now, to allow buffers to refill */
1036 if (dsound->state == STATE_PLAYING) {
1037 dsound->state = STATE_STARTING;
1039 else if (dsound->state == STATE_STOPPING) {
1040 dsound->state = STATE_STOPPED;
1043 /* how can we have an underrun if we aren't playing? */
1044 WARN("unexpected primary state (%ld)\n", dsound->state);
1046 #ifdef SYNC_CALLBACK
1047 /* DSOUND_callback may need this lock */
1048 LeaveCriticalSection(&(dsound->mixlock));
1050 if (DSOUND_PrimaryStop(dsound) != DS_OK)
1051 WARN("DSOUND_PrimaryStop failed\n");
1052 #ifdef SYNC_CALLBACK
1053 EnterCriticalSection(&(dsound->mixlock));
1055 if (dsound->hwbuf) {
1056 /* the Stop is supposed to reset play position to beginning of buffer */
1057 /* unfortunately, OSS is not able to do so, so get current pointer */
1058 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, NULL);
1060 LeaveCriticalSection(&(dsound->mixlock));
1061 WARN("IDsDriverBuffer_GetPosition failed\n");
1065 playpos = dsound->pwplay * dsound->fraglen;
1068 dsound->playpos = playpos;
1069 dsound->mixpos = writepos;
1071 maxq = dsound->buflen;
1072 if (maxq > frag) maxq = frag;
1073 memset(dsound->buffer, nfiller, dsound->buflen);
1078 frag = DSOUND_MixToPrimary(dsound, playpos, writepos, maxq, paused);
1079 if (forced) frag = maxq - inq;
1080 dsound->mixpos += frag;
1081 dsound->mixpos %= dsound->buflen;
1084 /* buffers have been filled, restart playback */
1085 if (dsound->state == STATE_STARTING) {
1086 dsound->state = STATE_PLAYING;
1088 else if (dsound->state == STATE_STOPPED) {
1089 /* the dsound is supposed to play if there's something to play
1090 * even if it is reported as stopped, so don't let this confuse you */
1091 dsound->state = STATE_STOPPING;
1093 LeaveCriticalSection(&(dsound->mixlock));
1095 if (DSOUND_PrimaryPlay(dsound) != DS_OK)
1096 WARN("DSOUND_PrimaryPlay failed\n");
1098 TRACE("starting playback\n");
1102 LeaveCriticalSection(&(dsound->mixlock));
1104 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
1105 if (dsound->state == STATE_STARTING) {
1106 if (DSOUND_PrimaryPlay(dsound) != DS_OK)
1107 WARN("DSOUND_PrimaryPlay failed\n");
1109 dsound->state = STATE_PLAYING;
1111 else if (dsound->state == STATE_STOPPING) {
1112 if (DSOUND_PrimaryStop(dsound) != DS_OK)
1113 WARN("DSOUND_PrimaryStop failed\n");
1115 dsound->state = STATE_STOPPED;
1120 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1122 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1123 DWORD start_time = GetTickCount();
1125 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
1126 TRACE("entering at %ld\n", start_time);
1128 if (dsound != This) {
1129 ERR("dsound died without killing us?\n");
1130 timeKillEvent(timerID);
1131 timeEndPeriod(DS_TIME_RES);
1135 RtlAcquireResourceShared(&(This->buffer_list_lock), TRUE);
1138 DSOUND_PerformMix(This);
1140 RtlReleaseResource(&(This->buffer_list_lock));
1142 end_time = GetTickCount();
1143 TRACE("completed processing at %ld, duration = %ld\n", end_time, end_time - start_time);
1146 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1148 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1149 TRACE("(%p,%x,%lx,%lx,%lx)\n",hwo,msg,dwUser,dw1,dw2);
1150 TRACE("entering at %ld, msg=%08x(%s)\n", GetTickCount(), msg,
1151 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
1152 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1153 if (msg == MM_WOM_DONE) {
1154 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
1155 if (This->pwqueue == (DWORD)-1) {
1156 TRACE("completed due to reset\n");
1159 /* it could be a bad idea to enter critical section here... if there's lock contention,
1160 * the resulting scheduling delays might obstruct the winmm player thread */
1161 #ifdef SYNC_CALLBACK
1162 EnterCriticalSection(&(This->mixlock));
1164 /* retrieve current values */
1165 fraglen = This->fraglen;
1166 buflen = This->buflen;
1167 pwplay = This->pwplay;
1168 playpos = pwplay * fraglen;
1169 mixpos = This->mixpos;
1170 /* check remaining mixed data */
1171 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1172 mixq = inq / fraglen;
1173 if ((inq - (mixq * fraglen)) > 0) mixq++;
1174 /* complete the playing buffer */
1175 TRACE("done playing primary pos=%ld\n", playpos);
1177 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1178 /* write new values */
1179 This->pwplay = pwplay;
1181 /* queue new buffer if we have data for it */
1182 if (inq>1) DSOUND_WaveQueue(This, inq-1);
1183 #ifdef SYNC_CALLBACK
1184 LeaveCriticalSection(&(This->mixlock));
1187 TRACE("completed\n");