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->wfx.nChannels * (dsb->wfx.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->wfx.wBitsPerSample == 8) {
184 if (dsb->dsound->wfx.wBitsPerSample == 8 &&
185 dsb->dsound->wfx.nChannels == dsb->wfx.nChannels) {
186 /* avoid needless 8->16->8 conversion */
188 if (dsb->wfx.nChannels==2)
192 fl = cvtU8toS16(*ibuf);
193 fr = (dsb->wfx.nChannels==2 ? cvtU8toS16(*(ibuf + 1)) : fl);
195 fl = *((INT16 *)ibuf);
196 fr = (dsb->wfx.nChannels==2 ? *(((INT16 *)ibuf) + 1) : fl);
199 if (dsb->dsound->wfx.nChannels == 2) {
200 if (dsb->dsound->wfx.wBitsPerSample == 8) {
201 *obuf = cvtS16toU8(fl);
202 *(obuf + 1) = cvtS16toU8(fr);
205 if (dsb->dsound->wfx.wBitsPerSample == 16) {
206 *((INT16 *)obuf) = fl;
207 *(((INT16 *)obuf) + 1) = fr;
211 if (dsb->dsound->wfx.nChannels == 1) {
213 if (dsb->dsound->wfx.wBitsPerSample == 8) {
214 *obuf = cvtS16toU8(fl);
217 if (dsb->dsound->wfx.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->wfx.nBlockAlign;
230 INT oAdvance = dsb->dsound->wfx.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->wfx.nSamplesPerSec) &&
238 (dsb->wfx.wBitsPerSample == dsb->dsound->wfx.wBitsPerSample) &&
239 (dsb->wfx.nChannels == dsb->dsound->wfx.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->wfx.nSamplesPerSec) {
253 TRACE("(%p) Same sample rate %ld = primary %ld\n", dsb,
254 dsb->freq, dsb->dsound->wfx.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->wfx.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;
289 while (ipos >= dsb->buflen)
296 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
300 INT16 *bps = (INT16 *) buf;
302 TRACE("(%p,%p,%d)\n",dsb,buf,len);
303 TRACE("left = %lx, right = %lx\n", dsb->cvolpan.dwTotalLeftAmpFactor,
304 dsb->cvolpan.dwTotalRightAmpFactor);
306 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->cvolpan.lPan == 0)) &&
307 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->cvolpan.lVolume == 0)) &&
308 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
309 return; /* Nothing to do */
311 /* If we end up with some bozo coder using panning or 3D sound */
312 /* with a mono primary buffer, it could sound very weird using */
313 /* this method. Oh well, tough patooties. */
315 switch (dsb->dsound->wfx.wBitsPerSample) {
317 /* 8-bit WAV is unsigned, but we need to operate */
318 /* on signed data for this to work properly */
319 switch (dsb->dsound->wfx.nChannels) {
321 for (i = 0; i < len; i++) {
322 INT val = *bpc - 128;
323 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
329 for (i = 0; i < len; i+=2) {
330 INT val = *bpc - 128;
331 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
334 val = (val * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
340 FIXME("doesn't support %d channels\n", dsb->dsound->wfx.nChannels);
345 /* 16-bit WAV is signed -- much better */
346 switch (dsb->dsound->wfx.nChannels) {
348 for (i = 0; i < len; i += 2) {
349 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
354 for (i = 0; i < len; i += 4) {
355 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
357 *bps = (*bps * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
362 FIXME("doesn't support %d channels\n", dsb->dsound->wfx.nChannels);
367 FIXME("doesn't support %d bit samples\n", dsb->dsound->wfx.wBitsPerSample);
372 static void *tmp_buffer;
373 static size_t tmp_buffer_len = 0;
375 static void *DSOUND_tmpbuffer(size_t len)
377 if (len>tmp_buffer_len) {
378 void *new_buffer = realloc(tmp_buffer, len);
380 tmp_buffer = new_buffer;
381 tmp_buffer_len = len;
388 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
390 INT i, len, ilen, temp, field, nBlockAlign, todo;
393 TRACE("(%p,%ld,%ld)\n",dsb,writepos,fraglen);
396 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
397 temp = MulDiv(dsb->dsound->wfx.nAvgBytesPerSec, dsb->buflen,
398 dsb->nAvgBytesPerSec) -
399 MulDiv(dsb->dsound->wfx.nAvgBytesPerSec, dsb->buf_mixpos,
400 dsb->nAvgBytesPerSec);
401 len = (len > temp) ? temp : len;
403 nBlockAlign = dsb->dsound->wfx.nBlockAlign;
404 len = len / nBlockAlign * nBlockAlign; /* data alignment */
407 /* This should only happen if we aren't looping and temp < nBlockAlign */
411 /* Been seeing segfaults in malloc() for some reason... */
412 TRACE("allocating buffer (size = %d)\n", len);
413 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
416 TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
418 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
419 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
420 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
421 (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
422 DSOUND_MixerVol(dsb, ibuf, len);
424 if (dsb->dsound->wfx.wBitsPerSample == 8) {
425 BYTE *obuf = dsb->dsound->buffer + writepos;
427 if ((writepos + len) <= dsb->dsound->buflen)
430 todo = dsb->dsound->buflen - writepos;
432 for (i = 0; i < todo; i++) {
433 /* 8-bit WAV is unsigned */
434 field = (*ibuf++ - 128);
435 field += (*obuf - 128);
436 if (field > 127) field = 127;
437 else if (field < -128) field = -128;
438 *obuf++ = field + 128;
443 obuf = dsb->dsound->buffer;
445 for (i = 0; i < todo; i++) {
446 /* 8-bit WAV is unsigned */
447 field = (*ibuf++ - 128);
448 field += (*obuf - 128);
449 if (field > 127) field = 127;
450 else if (field < -128) field = -128;
451 *obuf++ = field + 128;
455 INT16 *ibufs, *obufs;
457 ibufs = (INT16 *) ibuf;
458 obufs = (INT16 *)(dsb->dsound->buffer + writepos);
460 if ((writepos + len) <= dsb->dsound->buflen)
463 todo = (dsb->dsound->buflen - writepos) / 2;
465 for (i = 0; i < todo; i++) {
466 /* 16-bit WAV is signed */
469 if (field > 32767) field = 32767;
470 else if (field < -32768) field = -32768;
474 if (todo < (len / 2)) {
475 todo = (len / 2) - todo;
476 obufs = (INT16 *)dsb->dsound->buffer;
478 for (i = 0; i < todo; i++) {
479 /* 16-bit WAV is signed */
482 if (field > 32767) field = 32767;
483 else if (field < -32768) field = -32768;
489 if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
490 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
491 * not the MIX position... but if the sound buffer is bigger than our prebuffering
492 * (which must be the case for the streaming buffers that need this hack anyway)
493 * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
497 dsb->buf_mixpos += ilen;
499 if (dsb->buf_mixpos >= dsb->buflen) {
500 if (dsb->playflags & DSBPLAY_LOOPING) {
502 while (dsb->buf_mixpos >= dsb->buflen)
503 dsb->buf_mixpos -= dsb->buflen;
504 if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
505 dsb->leadin = FALSE; /* HACK: see above */
512 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
514 INT i, ilen, field, nBlockAlign, todo;
517 TRACE("(%p,%ld,%ld)\n",dsb,writepos,len);
519 nBlockAlign = dsb->dsound->wfx.nBlockAlign;
520 len = len / nBlockAlign * nBlockAlign; /* data alignment */
522 TRACE("allocating buffer (size = %ld)\n", len);
523 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
526 TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
528 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
529 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
530 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
531 (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
532 DSOUND_MixerVol(dsb, ibuf, len);
534 /* subtract instead of add, to phase out premixed data */
535 if (dsb->dsound->wfx.wBitsPerSample == 8) {
536 BYTE *obuf = dsb->dsound->buffer + writepos;
538 if ((writepos + len) <= dsb->dsound->buflen)
541 todo = dsb->dsound->buflen - writepos;
543 for (i = 0; i < todo; i++) {
544 /* 8-bit WAV is unsigned */
545 field = (*ibuf++ - 128);
546 field -= (*obuf - 128);
547 if (field > 127) field = 127;
548 else if (field < -128) field = -128;
549 *obuf++ = field + 128;
554 obuf = dsb->dsound->buffer;
556 for (i = 0; i < todo; i++) {
557 /* 8-bit WAV is unsigned */
558 field = (*ibuf++ - 128);
559 field -= (*obuf - 128);
560 if (field > 127) field = 127;
561 else if (field < -128) field = -128;
562 *obuf++ = field + 128;
566 INT16 *ibufs, *obufs;
568 ibufs = (INT16 *) ibuf;
569 obufs = (INT16 *)(dsb->dsound->buffer + writepos);
571 if ((writepos + len) <= dsb->dsound->buflen)
574 todo = (dsb->dsound->buflen - writepos) / 2;
576 for (i = 0; i < todo; i++) {
577 /* 16-bit WAV is signed */
580 if (field > 32767) field = 32767;
581 else if (field < -32768) field = -32768;
585 if (todo < (len / 2)) {
586 todo = (len / 2) - todo;
587 obufs = (INT16 *)dsb->dsound->buffer;
589 for (i = 0; i < todo; i++) {
590 /* 16-bit WAV is signed */
593 if (field > 32767) field = 32767;
594 else if (field < -32768) field = -32768;
601 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
603 DWORD size, flen, len, npos, nlen;
604 INT iAdvance = dsb->wfx.nBlockAlign;
605 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
606 /* determine amount of premixed data to cancel */
608 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
609 dsb->primary_mixpos - writepos;
611 TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
613 /* backtrack the mix position */
614 size = primary_done / oAdvance;
615 flen = size * dsb->freqAdjust;
616 len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
617 flen &= (1<<DSOUND_FREQSHIFT)-1;
618 while (dsb->freqAcc < flen) {
620 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
623 npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
624 dsb->buf_mixpos - len;
625 if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
626 /* stop backtracking at startpos */
627 npos = dsb->startpos;
628 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
629 dsb->buf_mixpos - npos;
631 nlen = len / dsb->wfx.nBlockAlign;
632 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
633 nlen *= dsb->dsound->wfx.nBlockAlign;
635 ((dsb->primary_mixpos < nlen) ? dsb->dsound->buflen : 0) +
636 dsb->primary_mixpos - nlen;
639 dsb->freqAcc -= flen;
640 dsb->buf_mixpos = npos;
641 dsb->primary_mixpos = writepos;
643 TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
644 dsb->buf_mixpos, dsb->primary_mixpos, len);
646 if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
649 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
652 DWORD i, size, flen, len, npos, nlen;
653 INT iAdvance = dsb->wfx.nBlockAlign;
654 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
655 /* determine amount of premixed data to cancel */
657 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
658 dsb->buf_mixpos - buf_writepos;
661 WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
662 /* since this is not implemented yet, just cancel *ALL* prebuffering for now
663 * (which is faster anyway when there's only a single secondary buffer) */
664 dsb->dsound->need_remix = TRUE;
667 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
670 EnterCriticalSection(&dsb->lock);
671 if (dsb->state == STATE_PLAYING) {
672 #if 0 /* this may not be quite reliable yet */
673 dsb->need_remix = TRUE;
675 dsb->dsound->need_remix = TRUE;
678 LeaveCriticalSection(&dsb->lock);
681 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
684 /* determine this buffer's write position */
685 DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, dsb->state & dsb->dsound->state, writepos,
686 writepos, dsb->primary_mixpos, dsb->buf_mixpos);
687 /* determine how much already-mixed data exists */
689 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
690 dsb->buf_mixpos - buf_writepos;
692 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
693 dsb->primary_mixpos - writepos;
695 ((dsb->dsound->mixpos < writepos) ? dsb->dsound->buflen : 0) +
696 dsb->dsound->mixpos - writepos;
698 ((buf_writepos < dsb->playpos) ? dsb->buflen : 0) +
699 buf_writepos - dsb->playpos;
700 DWORD buf_left = dsb->buflen - buf_writepos;
703 TRACE("(%p,%ld,%ld,%ld)\n",dsb,playpos,writepos,mixlen);
704 TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
705 TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
706 TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
708 TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
710 /* check for notification positions */
711 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
712 dsb->state != STATE_STARTING) {
713 DSOUND_CheckEvent(dsb, played);
716 /* save write position for non-GETCURRENTPOSITION2... */
717 dsb->playpos = buf_writepos;
719 /* check whether CalcPlayPosition detected a mixing underrun */
720 if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
721 /* it did, but did we have more to play? */
722 if ((dsb->playflags & DSBPLAY_LOOPING) ||
723 (dsb->buf_mixpos < dsb->buflen)) {
724 /* yes, have to recover */
725 ERR("underrun on sound buffer %p\n", dsb);
726 TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
728 dsb->primary_mixpos = writepos;
731 /* determine how far ahead we should mix */
732 if (((dsb->playflags & DSBPLAY_LOOPING) ||
733 (dsb->leadin && (dsb->probably_valid_to != 0))) &&
734 !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
735 /* if this is a streaming buffer, it typically means that
736 * we should defer mixing past probably_valid_to as long
737 * as we can, to avoid unnecessary remixing */
738 /* the heavy-looking calculations shouldn't be that bad,
739 * as any game isn't likely to be have more than 1 or 2
740 * streaming buffers in use at any time anyway... */
741 DWORD probably_valid_left =
742 (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
743 ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
744 dsb->probably_valid_to - buf_writepos;
745 /* check for leadin condition */
746 if ((probably_valid_left == 0) &&
747 (dsb->probably_valid_to == dsb->startpos) &&
749 probably_valid_left = dsb->buflen;
750 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
751 dsb->probably_valid_to, probably_valid_left);
752 /* check whether the app's time is already up */
753 if (probably_valid_left < dsb->writelead) {
754 WARN("probably_valid_to now within writelead, possible streaming underrun\n");
755 /* once we pass the point of no return,
756 * no reason to hold back anymore */
757 dsb->probably_valid_to = (DWORD)-1;
758 /* we just have to go ahead and mix what we have,
759 * there's no telling what the app is thinking anyway */
761 /* adjust for our frequency and our sample size */
762 probably_valid_left = MulDiv(probably_valid_left,
763 1 << DSOUND_FREQSHIFT,
764 dsb->wfx.nBlockAlign * dsb->freqAdjust) *
765 dsb->dsound->wfx.nBlockAlign;
766 /* check whether to clip mix_len */
767 if (probably_valid_left < mixlen) {
768 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
769 mixlen = probably_valid_left;
773 /* cut mixlen with what's already been mixed */
774 if (mixlen < primary_done) {
775 /* huh? and still CalcPlayPosition didn't
776 * detect an underrun? */
777 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
780 len = mixlen - primary_done;
781 TRACE("remaining mixlen=%ld\n", len);
783 if (len < dsb->dsound->fraglen) {
784 /* smaller than a fragment, wait until it gets larger
785 * before we take the mixing overhead */
786 TRACE("mixlen not worth it, deferring mixing\n");
791 /* ok, we know how much to mix, let's go */
792 still_behind = (adv_done > primary_done);
794 slen = dsb->dsound->buflen - dsb->primary_mixpos;
795 if (slen > len) slen = len;
796 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
798 if ((dsb->primary_mixpos < dsb->dsound->mixpos) &&
799 (dsb->primary_mixpos + slen >= dsb->dsound->mixpos))
800 still_behind = FALSE;
802 dsb->primary_mixpos += slen; len -= slen;
803 while (dsb->primary_mixpos >= dsb->dsound->buflen)
804 dsb->primary_mixpos -= dsb->dsound->buflen;
806 if ((dsb->state == STATE_STOPPED) || !slen) break;
808 TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->mixpos);
809 TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
812 /* check if buffer should be considered complete */
813 if (buf_left < dsb->writelead &&
814 !(dsb->playflags & DSBPLAY_LOOPING)) {
815 dsb->state = STATE_STOPPED;
817 dsb->last_playpos = 0;
820 DSOUND_CheckEvent(dsb, buf_left);
823 /* return how far we think the primary buffer can
824 * advance its underrun detector...*/
825 if (still_behind) return 0;
826 if ((mixlen - len) < primary_done) return 0;
827 slen = ((dsb->primary_mixpos < dsb->dsound->mixpos) ?
828 dsb->dsound->buflen : 0) + dsb->primary_mixpos -
831 /* the primary_done and still_behind checks above should have worked */
832 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
838 static DWORD DSOUND_MixToPrimary(IDirectSoundImpl *dsound, DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
840 INT i, len, maxlen = 0;
841 IDirectSoundBufferImpl *dsb;
843 TRACE("(%ld,%ld,%ld,%d)\n", playpos, writepos, mixlen, recover);
844 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
845 dsb = dsound->buffers[i];
847 if (!dsb || !dsb->lpVtbl)
849 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
850 TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
851 EnterCriticalSection(&(dsb->lock));
852 if (dsb->state == STATE_STOPPING) {
853 DSOUND_MixCancel(dsb, writepos, TRUE);
854 dsb->state = STATE_STOPPED;
855 DSOUND_CheckEvent(dsb, 0);
857 if ((dsb->state == STATE_STARTING) || recover) {
858 dsb->primary_mixpos = writepos;
859 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
860 dsb->need_remix = FALSE;
862 else if (dsb->need_remix) {
863 DSOUND_MixCancel(dsb, writepos, TRUE);
864 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
865 dsb->need_remix = FALSE;
867 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
868 if (dsb->state == STATE_STARTING)
869 dsb->state = STATE_PLAYING;
870 maxlen = (len > maxlen) ? len : maxlen;
872 LeaveCriticalSection(&(dsb->lock));
879 static void DSOUND_MixReset(IDirectSoundImpl *dsound, DWORD writepos)
882 IDirectSoundBufferImpl *dsb;
885 TRACE("(%ld)\n", writepos);
887 /* the sound of silence */
888 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
890 /* reset all buffer mix positions */
891 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
892 dsb = dsound->buffers[i];
894 if (!dsb || !dsb->lpVtbl)
896 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
897 TRACE("Resetting %p\n", dsb);
898 EnterCriticalSection(&(dsb->lock));
899 if (dsb->state == STATE_STOPPING) {
900 dsb->state = STATE_STOPPED;
902 else if (dsb->state == STATE_STARTING) {
905 DSOUND_MixCancel(dsb, writepos, FALSE);
906 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
907 dsb->need_remix = FALSE;
909 LeaveCriticalSection(&(dsb->lock));
913 /* wipe out premixed data */
914 if (dsound->mixpos < writepos) {
915 memset(dsound->buffer + writepos, nfiller, dsound->buflen - writepos);
916 memset(dsound->buffer, nfiller, dsound->mixpos);
918 memset(dsound->buffer + writepos, nfiller, dsound->mixpos - writepos);
921 /* reset primary mix position */
922 dsound->mixpos = writepos;
925 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
927 TRACE("(%p,%ld)\n",dsound,writepos);
928 if (dsound->need_remix) {
929 DSOUND_MixReset(dsound, writepos);
930 dsound->need_remix = FALSE;
931 /* maximize Half-Life performance */
932 dsound->prebuf = ds_snd_queue_min;
933 dsound->precount = 0;
936 if (dsound->precount >= 4) {
937 if (dsound->prebuf < ds_snd_queue_max)
939 dsound->precount = 0;
942 TRACE("premix adjust: %d\n", dsound->prebuf);
945 void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
947 TRACE("(%p,%ld)\n",dsound,mixq);
948 if (mixq + dsound->pwqueue > ds_hel_queue) mixq = ds_hel_queue - dsound->pwqueue;
949 TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
950 for (; mixq; mixq--) {
951 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
953 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
958 /* #define SYNC_CALLBACK */
960 void DSOUND_PerformMix(IDirectSoundImpl *dsound)
968 /* the sound of silence */
969 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
971 /* whether the primary is forced to play even without secondary buffers */
972 forced = ((dsound->state == STATE_PLAYING) || (dsound->state == STATE_STARTING));
974 if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
975 BOOL paused = ((dsound->state == STATE_STOPPED) || (dsound->state == STATE_STARTING));
976 /* FIXME: document variables */
977 DWORD playpos, writepos, inq, maxq, frag;
979 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, &writepos);
981 WARN("IDsDriverBuffer_GetPosition failed\n");
984 /* Well, we *could* do Just-In-Time mixing using the writepos,
985 * but that's a little bit ambitious and unnecessary... */
986 /* rather add our safety margin to the writepos, if we're playing */
988 writepos += dsound->writelead;
989 while (writepos >= dsound->buflen)
990 writepos -= dsound->buflen;
991 } else writepos = playpos;
993 playpos = dsound->pwplay * dsound->fraglen;
996 writepos += ds_hel_margin * dsound->fraglen;
997 while (writepos >= dsound->buflen)
998 writepos -= dsound->buflen;
1001 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld, buflen=%ld\n",
1002 playpos,writepos,dsound->playpos,dsound->mixpos,dsound->buflen);
1003 assert(dsound->playpos < dsound->buflen);
1004 /* wipe out just-played sound data */
1005 if (playpos < dsound->playpos) {
1006 memset(dsound->buffer + dsound->playpos, nfiller, dsound->buflen - dsound->playpos);
1007 memset(dsound->buffer, nfiller, playpos);
1009 memset(dsound->buffer + dsound->playpos, nfiller, playpos - dsound->playpos);
1011 dsound->playpos = playpos;
1013 EnterCriticalSection(&(dsound->mixlock));
1015 /* reset mixing if necessary */
1016 DSOUND_CheckReset(dsound, writepos);
1018 /* check how much prebuffering is left */
1019 inq = dsound->mixpos;
1021 inq += dsound->buflen;
1024 /* find the maximum we can prebuffer */
1027 if (maxq < writepos)
1028 maxq += dsound->buflen;
1030 } else maxq = dsound->buflen;
1032 /* clip maxq to dsound->prebuf */
1033 frag = dsound->prebuf * dsound->fraglen;
1034 if (maxq > frag) maxq = frag;
1036 /* check for consistency */
1038 /* the playback position must have passed our last
1039 * mixed position, i.e. it's an underrun, or we have
1040 * nothing more to play */
1041 TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
1043 /* stop the playback now, to allow buffers to refill */
1044 if (dsound->state == STATE_PLAYING) {
1045 dsound->state = STATE_STARTING;
1047 else if (dsound->state == STATE_STOPPING) {
1048 dsound->state = STATE_STOPPED;
1051 /* how can we have an underrun if we aren't playing? */
1052 WARN("unexpected primary state (%ld)\n", dsound->state);
1054 #ifdef SYNC_CALLBACK
1055 /* DSOUND_callback may need this lock */
1056 LeaveCriticalSection(&(dsound->mixlock));
1058 if (DSOUND_PrimaryStop(dsound) != DS_OK)
1059 WARN("DSOUND_PrimaryStop failed\n");
1060 #ifdef SYNC_CALLBACK
1061 EnterCriticalSection(&(dsound->mixlock));
1063 if (dsound->hwbuf) {
1064 /* the Stop is supposed to reset play position to beginning of buffer */
1065 /* unfortunately, OSS is not able to do so, so get current pointer */
1066 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, NULL);
1068 LeaveCriticalSection(&(dsound->mixlock));
1069 WARN("IDsDriverBuffer_GetPosition failed\n");
1073 playpos = dsound->pwplay * dsound->fraglen;
1076 dsound->playpos = playpos;
1077 dsound->mixpos = writepos;
1079 maxq = dsound->buflen;
1080 if (maxq > frag) maxq = frag;
1081 memset(dsound->buffer, nfiller, dsound->buflen);
1086 frag = DSOUND_MixToPrimary(dsound, playpos, writepos, maxq, paused);
1087 if (forced) frag = maxq - inq;
1088 dsound->mixpos += frag;
1089 while (dsound->mixpos >= dsound->buflen)
1090 dsound->mixpos -= dsound->buflen;
1093 /* buffers have been filled, restart playback */
1094 if (dsound->state == STATE_STARTING) {
1095 dsound->state = STATE_PLAYING;
1097 else if (dsound->state == STATE_STOPPED) {
1098 /* the dsound is supposed to play if there's something to play
1099 * even if it is reported as stopped, so don't let this confuse you */
1100 dsound->state = STATE_STOPPING;
1102 LeaveCriticalSection(&(dsound->mixlock));
1104 if (DSOUND_PrimaryPlay(dsound) != DS_OK)
1105 WARN("DSOUND_PrimaryPlay failed\n");
1107 TRACE("starting playback\n");
1111 LeaveCriticalSection(&(dsound->mixlock));
1113 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
1114 if (dsound->state == STATE_STARTING) {
1115 if (DSOUND_PrimaryPlay(dsound) != DS_OK)
1116 WARN("DSOUND_PrimaryPlay failed\n");
1118 dsound->state = STATE_PLAYING;
1120 else if (dsound->state == STATE_STOPPING) {
1121 if (DSOUND_PrimaryStop(dsound) != DS_OK)
1122 WARN("DSOUND_PrimaryStop failed\n");
1124 dsound->state = STATE_STOPPED;
1129 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1131 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1132 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
1133 TRACE("entering at %ld\n", GetTickCount());
1135 if (dsound != This) {
1136 ERR("dsound died without killing us?\n");
1137 timeKillEvent(timerID);
1138 timeEndPeriod(DS_TIME_RES);
1142 RtlAcquireResourceShared(&(This->lock), TRUE);
1145 DSOUND_PerformMix(This);
1148 RtlReleaseResource(&(This->lock));
1150 TRACE("completed processing at %ld\n", GetTickCount());
1153 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1155 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1156 TRACE("(%p,%x,%lx,%lx,%lx)\n",hwo,msg,dwUser,dw1,dw2);
1157 TRACE("entering at %ld, msg=%08x(%s)\n", GetTickCount(), msg,
1158 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
1159 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1160 if (msg == MM_WOM_DONE) {
1161 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
1162 if (This->pwqueue == (DWORD)-1) {
1163 TRACE("completed due to reset\n");
1166 /* it could be a bad idea to enter critical section here... if there's lock contention,
1167 * the resulting scheduling delays might obstruct the winmm player thread */
1168 #ifdef SYNC_CALLBACK
1169 EnterCriticalSection(&(This->mixlock));
1171 /* retrieve current values */
1172 fraglen = This->fraglen;
1173 buflen = This->buflen;
1174 pwplay = This->pwplay;
1175 playpos = pwplay * fraglen;
1176 mixpos = This->mixpos;
1177 /* check remaining mixed data */
1178 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1179 mixq = inq / fraglen;
1180 if ((inq - (mixq * fraglen)) > 0) mixq++;
1181 /* complete the playing buffer */
1182 TRACE("done playing primary pos=%ld\n", playpos);
1184 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1185 /* write new values */
1186 This->pwplay = pwplay;
1188 /* queue new buffer if we have data for it */
1189 if (inq>1) DSOUND_WaveQueue(This, inq-1);
1190 #ifdef SYNC_CALLBACK
1191 LeaveCriticalSection(&(This->mixlock));
1194 TRACE("completed\n");