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
24 #include <math.h> /* Insomnia - pow() function */
26 #define NONAMELESSSTRUCT
27 #define NONAMELESSUNION
33 #include "wine/debug.h"
36 #include "dsound_private.h"
38 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
40 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
43 TRACE("(%p)\n",volpan);
45 TRACE("Vol=%ld Pan=%ld\n", volpan->lVolume, volpan->lPan);
46 /* the AmpFactors are expressed in 16.16 fixed point */
47 volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
48 /* FIXME: dwPan{Left|Right}AmpFactor */
50 /* FIXME: use calculated vol and pan ampfactors */
51 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
52 volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
53 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
54 volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
56 TRACE("left = %lx, right = %lx\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
59 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
62 TRACE("(%p)\n",volpan);
64 TRACE("left=%lx, right=%lx\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
65 if (volpan->dwTotalLeftAmpFactor==0)
68 left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
69 if (volpan->dwTotalRightAmpFactor==0)
72 right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
75 volpan->lVolume=right;
76 volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
81 volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
83 if (volpan->lVolume < -10000)
84 volpan->lVolume=-10000;
85 volpan->lPan=right-left;
86 if (volpan->lPan < -10000)
89 TRACE("Vol=%ld Pan=%ld\n", volpan->lVolume, volpan->lPan);
92 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
96 /* calculate the 10ms write lead */
97 dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
100 void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len)
104 LPDSBPOSITIONNOTIFY event;
105 TRACE("(%p,%d)\n",dsb,len);
107 if (dsb->nrofnotifies == 0)
110 TRACE("(%p) buflen = %ld, playpos = %ld, len = %d\n",
111 dsb, dsb->buflen, dsb->playpos, len);
112 for (i = 0; i < dsb->nrofnotifies ; i++) {
113 event = dsb->notifies + i;
114 offset = event->dwOffset;
115 TRACE("checking %d, position %ld, event = %p\n",
116 i, offset, event->hEventNotify);
117 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
118 /* OK. [Inside DirectX, p274] */
120 /* This also means we can't sort the entries by offset, */
121 /* because DSBPN_OFFSETSTOP == -1 */
122 if (offset == DSBPN_OFFSETSTOP) {
123 if (dsb->state == STATE_STOPPED) {
124 SetEvent(event->hEventNotify);
125 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
130 if ((dsb->playpos + len) >= dsb->buflen) {
131 if ((offset < ((dsb->playpos + len) % dsb->buflen)) ||
132 (offset >= dsb->playpos)) {
133 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
134 SetEvent(event->hEventNotify);
137 if ((offset >= dsb->playpos) && (offset < (dsb->playpos + len))) {
138 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
139 SetEvent(event->hEventNotify);
145 /* WAV format info can be found at:
147 * http://www.cwi.nl/ftp/audio/AudioFormats.part2
148 * ftp://ftp.cwi.nl/pub/audio/RIFF-format
150 * Import points to remember:
151 * 8-bit WAV is unsigned
152 * 16-bit WAV is signed
154 /* Use the same formulas as pcmconverter.c */
155 static inline INT16 cvtU8toS16(BYTE b)
157 return (short)((b+(b << 8))-32768);
160 static inline BYTE cvtS16toU8(INT16 s)
162 return (s >> 8) ^ (unsigned char)0x80;
165 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, BYTE *ibuf, BYTE *obuf )
167 DirectSoundDevice * device = dsb->dsound->device;
170 if (dsb->pwfx->wBitsPerSample == 8) {
171 if (device->pwfx->wBitsPerSample == 8 &&
172 device->pwfx->nChannels == dsb->pwfx->nChannels) {
173 /* avoid needless 8->16->8 conversion */
175 if (dsb->pwfx->nChannels==2)
179 fl = cvtU8toS16(*ibuf);
180 fr = (dsb->pwfx->nChannels==2 ? cvtU8toS16(*(ibuf + 1)) : fl);
182 fl = *((INT16 *)ibuf);
183 fr = (dsb->pwfx->nChannels==2 ? *(((INT16 *)ibuf) + 1) : fl);
186 if (device->pwfx->nChannels == 2) {
187 if (device->pwfx->wBitsPerSample == 8) {
188 *obuf = cvtS16toU8(fl);
189 *(obuf + 1) = cvtS16toU8(fr);
192 if (device->pwfx->wBitsPerSample == 16) {
193 *((INT16 *)obuf) = fl;
194 *(((INT16 *)obuf) + 1) = fr;
198 if (device->pwfx->nChannels == 1) {
200 if (device->pwfx->wBitsPerSample == 8) {
201 *obuf = cvtS16toU8(fl);
204 if (device->pwfx->wBitsPerSample == 16) {
205 *((INT16 *)obuf) = fl;
211 /* Now with PerfectPitch (tm) technology */
212 static INT DSOUND_MixerNorm(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
214 INT i, size, ipos, ilen;
216 INT iAdvance = dsb->pwfx->nBlockAlign;
217 INT oAdvance = dsb->dsound->device->pwfx->nBlockAlign;
219 ibp = dsb->buffer->memory + dsb->buf_mixpos;
222 TRACE("(%p, %p, %p), buf_mixpos=%ld\n", dsb, ibp, obp, dsb->buf_mixpos);
223 /* Check for the best case */
224 if ((dsb->freq == dsb->dsound->device->pwfx->nSamplesPerSec) &&
225 (dsb->pwfx->wBitsPerSample == dsb->dsound->device->pwfx->wBitsPerSample) &&
226 (dsb->pwfx->nChannels == dsb->dsound->device->pwfx->nChannels)) {
227 INT bytesleft = dsb->buflen - dsb->buf_mixpos;
228 TRACE("(%p) Best case\n", dsb);
229 if (len <= bytesleft )
230 CopyMemory(obp, ibp, len);
232 CopyMemory(obp, ibp, bytesleft);
233 CopyMemory(obp + bytesleft, dsb->buffer->memory, len - bytesleft);
238 /* Check for same sample rate */
239 if (dsb->freq == dsb->dsound->device->pwfx->nSamplesPerSec) {
240 TRACE("(%p) Same sample rate %ld = primary %ld\n", dsb,
241 dsb->freq, dsb->dsound->device->pwfx->nSamplesPerSec);
243 for (i = 0; i < len; i += oAdvance) {
244 cp_fields(dsb, ibp, obp );
248 if (ibp >= (BYTE *)(dsb->buffer->memory + dsb->buflen))
249 ibp = dsb->buffer->memory; /* wrap */
254 /* Mix in different sample rates */
256 /* New PerfectPitch(tm) Technology (c) 1998 Rob Riggs */
257 /* Patent Pending :-] */
259 /* Patent enhancements (c) 2000 Ove KÃ¥ven,
260 * TransGaming Technologies Inc. */
262 /* FIXME("(%p) Adjusting frequency: %ld -> %ld (need optimization)\n",
263 dsb, dsb->freq, dsb->dsound->device->pwfx->nSamplesPerSec); */
265 size = len / oAdvance;
267 ipos = dsb->buf_mixpos;
268 for (i = 0; i < size; i++) {
269 cp_fields(dsb, (dsb->buffer->memory + ipos), obp);
271 dsb->freqAcc += dsb->freqAdjust;
272 if (dsb->freqAcc >= (1<<DSOUND_FREQSHIFT)) {
273 ULONG adv = (dsb->freqAcc>>DSOUND_FREQSHIFT) * iAdvance;
274 dsb->freqAcc &= (1<<DSOUND_FREQSHIFT)-1;
275 ipos += adv; ilen += adv;
282 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
286 INT16 *bps = (INT16 *) buf;
288 TRACE("(%p,%p,%d)\n",dsb,buf,len);
289 TRACE("left = %lx, right = %lx\n", dsb->cvolpan.dwTotalLeftAmpFactor,
290 dsb->cvolpan.dwTotalRightAmpFactor);
292 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->cvolpan.lPan == 0)) &&
293 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->cvolpan.lVolume == 0)) &&
294 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
295 return; /* Nothing to do */
297 /* If we end up with some bozo coder using panning or 3D sound */
298 /* with a mono primary buffer, it could sound very weird using */
299 /* this method. Oh well, tough patooties. */
301 switch (dsb->dsound->device->pwfx->wBitsPerSample) {
303 /* 8-bit WAV is unsigned, but we need to operate */
304 /* on signed data for this to work properly */
305 switch (dsb->dsound->device->pwfx->nChannels) {
307 for (i = 0; i < len; i++) {
308 INT val = *bpc - 128;
309 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
315 for (i = 0; i < len; i+=2) {
316 INT val = *bpc - 128;
317 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
320 val = (val * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
326 FIXME("doesn't support %d channels\n", dsb->dsound->device->pwfx->nChannels);
331 /* 16-bit WAV is signed -- much better */
332 switch (dsb->dsound->device->pwfx->nChannels) {
334 for (i = 0; i < len; i += 2) {
335 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
340 for (i = 0; i < len; i += 4) {
341 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
343 *bps = (*bps * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
348 FIXME("doesn't support %d channels\n", dsb->dsound->device->pwfx->nChannels);
353 FIXME("doesn't support %d bit samples\n", dsb->dsound->device->pwfx->wBitsPerSample);
358 static LPBYTE DSOUND_tmpbuffer(DirectSoundDevice *device, DWORD len)
360 TRACE("(%p,%ld)\n", device, len);
362 if (len > device->tmp_buffer_len) {
363 if (device->tmp_buffer)
364 device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, device->tmp_buffer, len);
366 device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
368 device->tmp_buffer_len = len;
371 return device->tmp_buffer;
374 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
376 INT i, len, ilen, field, todo;
379 TRACE("(%p,%ld,%ld)\n",dsb,writepos,fraglen);
382 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
383 int secondary_remainder = dsb->buflen - dsb->buf_mixpos;
384 int adjusted_remainder = MulDiv(dsb->dsound->device->pwfx->nAvgBytesPerSec, secondary_remainder, dsb->nAvgBytesPerSec);
385 assert(adjusted_remainder >= 0);
386 TRACE("secondary_remainder = %d, adjusted_remainder = %d, len = %d\n", secondary_remainder, adjusted_remainder, len);
387 if (adjusted_remainder < len) {
388 TRACE("clipping len to remainder of secondary buffer\n");
389 len = adjusted_remainder;
395 if (len % dsb->dsound->device->pwfx->nBlockAlign) {
396 INT nBlockAlign = dsb->dsound->device->pwfx->nBlockAlign;
397 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
398 len = (len / nBlockAlign) * nBlockAlign; /* data alignment */
401 if ((buf = ibuf = DSOUND_tmpbuffer(dsb->dsound->device, len)) == NULL)
404 TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
406 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
407 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
408 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
409 (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
410 DSOUND_MixerVol(dsb, ibuf, len);
412 if (dsb->dsound->device->pwfx->wBitsPerSample == 8) {
413 BYTE *obuf = dsb->dsound->device->buffer + writepos;
415 if ((writepos + len) <= dsb->dsound->device->buflen)
418 todo = dsb->dsound->device->buflen - writepos;
420 for (i = 0; i < todo; i++) {
421 /* 8-bit WAV is unsigned */
422 field = (*ibuf++ - 128);
423 field += (*obuf - 128);
424 if (field > 127) field = 127;
425 else if (field < -128) field = -128;
426 *obuf++ = field + 128;
431 obuf = dsb->dsound->device->buffer;
433 for (i = 0; i < todo; i++) {
434 /* 8-bit WAV is unsigned */
435 field = (*ibuf++ - 128);
436 field += (*obuf - 128);
437 if (field > 127) field = 127;
438 else if (field < -128) field = -128;
439 *obuf++ = field + 128;
443 INT16 *ibufs, *obufs;
445 ibufs = (INT16 *) ibuf;
446 obufs = (INT16 *)(dsb->dsound->device->buffer + writepos);
448 if ((writepos + len) <= dsb->dsound->device->buflen)
451 todo = (dsb->dsound->device->buflen - writepos) / 2;
453 for (i = 0; i < todo; i++) {
454 /* 16-bit WAV is signed */
457 if (field > 32767) field = 32767;
458 else if (field < -32768) field = -32768;
462 if (todo < (len / 2)) {
463 todo = (len / 2) - todo;
464 obufs = (INT16 *)dsb->dsound->device->buffer;
466 for (i = 0; i < todo; i++) {
467 /* 16-bit WAV is signed */
470 if (field > 32767) field = 32767;
471 else if (field < -32768) field = -32768;
477 if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
478 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
479 * not the MIX position... but if the sound buffer is bigger than our prebuffering
480 * (which must be the case for the streaming buffers that need this hack anyway)
481 * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
485 dsb->buf_mixpos += ilen;
487 if (dsb->buf_mixpos >= dsb->buflen) {
488 if (dsb->playflags & DSBPLAY_LOOPING) {
490 dsb->buf_mixpos %= dsb->buflen;
491 if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
492 dsb->leadin = FALSE; /* HACK: see above */
499 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
505 TRACE("(%p,%ld,%ld)\n",dsb,writepos,len);
507 if (len % dsb->dsound->device->pwfx->nBlockAlign) {
508 INT nBlockAlign = dsb->dsound->device->pwfx->nBlockAlign;
509 ERR("length not a multiple of block size, len = %ld, block size = %d\n", len, nBlockAlign);
510 len = (len / nBlockAlign) * nBlockAlign; /* data alignment */
513 if ((buf = ibuf = DSOUND_tmpbuffer(dsb->dsound->device, len)) == NULL)
516 TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
518 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
519 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
520 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
521 (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
522 DSOUND_MixerVol(dsb, ibuf, len);
524 /* subtract instead of add, to phase out premixed data */
525 if (dsb->dsound->device->pwfx->wBitsPerSample == 8) {
526 BYTE *obuf = dsb->dsound->device->buffer + writepos;
528 if ((writepos + len) <= dsb->dsound->device->buflen)
531 todo = dsb->dsound->device->buflen - writepos;
533 for (i = 0; i < todo; i++) {
534 /* 8-bit WAV is unsigned */
535 field = (*ibuf++ - 128);
536 field -= (*obuf - 128);
537 if (field > 127) field = 127;
538 else if (field < -128) field = -128;
539 *obuf++ = field + 128;
544 obuf = dsb->dsound->device->buffer;
546 for (i = 0; i < todo; i++) {
547 /* 8-bit WAV is unsigned */
548 field = (*ibuf++ - 128);
549 field -= (*obuf - 128);
550 if (field > 127) field = 127;
551 else if (field < -128) field = -128;
552 *obuf++ = field + 128;
556 INT16 *ibufs, *obufs;
558 ibufs = (INT16 *) ibuf;
559 obufs = (INT16 *)(dsb->dsound->device->buffer + writepos);
561 if ((writepos + len) <= dsb->dsound->device->buflen)
564 todo = (dsb->dsound->device->buflen - writepos) / 2;
566 for (i = 0; i < todo; i++) {
567 /* 16-bit WAV is signed */
570 if (field > 32767) field = 32767;
571 else if (field < -32768) field = -32768;
575 if (todo < (len / 2)) {
576 todo = (len / 2) - todo;
577 obufs = (INT16 *)dsb->dsound->device->buffer;
579 for (i = 0; i < todo; i++) {
580 /* 16-bit WAV is signed */
583 if (field > 32767) field = 32767;
584 else if (field < -32768) field = -32768;
591 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
593 DWORD size, flen, len, npos, nlen;
594 INT iAdvance = dsb->pwfx->nBlockAlign;
595 INT oAdvance = dsb->dsound->device->pwfx->nBlockAlign;
596 /* determine amount of premixed data to cancel */
598 ((dsb->primary_mixpos < writepos) ? dsb->dsound->device->buflen : 0) +
599 dsb->primary_mixpos - writepos;
601 TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
603 /* backtrack the mix position */
604 size = primary_done / oAdvance;
605 flen = size * dsb->freqAdjust;
606 len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
607 flen &= (1<<DSOUND_FREQSHIFT)-1;
608 while (dsb->freqAcc < flen) {
610 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
613 npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
614 dsb->buf_mixpos - len;
615 if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
616 /* stop backtracking at startpos */
617 npos = dsb->startpos;
618 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
619 dsb->buf_mixpos - npos;
621 nlen = len / dsb->pwfx->nBlockAlign;
622 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
623 nlen *= dsb->dsound->device->pwfx->nBlockAlign;
625 ((dsb->primary_mixpos < nlen) ? dsb->dsound->device->buflen : 0) +
626 dsb->primary_mixpos - nlen;
629 dsb->freqAcc -= flen;
630 dsb->buf_mixpos = npos;
631 dsb->primary_mixpos = writepos;
633 TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
634 dsb->buf_mixpos, dsb->primary_mixpos, len);
636 if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
639 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
642 DWORD i, size, flen, len, npos, nlen;
643 INT iAdvance = dsb->pwfx->nBlockAlign;
644 INT oAdvance = dsb->dsound->device->pwfx->nBlockAlign;
645 /* determine amount of premixed data to cancel */
647 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
648 dsb->buf_mixpos - buf_writepos;
651 WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
652 /* since this is not implemented yet, just cancel *ALL* prebuffering for now
653 * (which is faster anyway when there's only a single secondary buffer) */
654 dsb->dsound->device->need_remix = TRUE;
657 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
660 EnterCriticalSection(&dsb->lock);
661 if (dsb->state == STATE_PLAYING)
662 dsb->dsound->device->need_remix = TRUE;
663 LeaveCriticalSection(&dsb->lock);
666 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
669 /* determine this buffer's write position */
670 DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, writepos, writepos);
671 /* determine how much already-mixed data exists */
673 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
674 dsb->buf_mixpos - buf_writepos;
676 ((dsb->primary_mixpos < writepos) ? dsb->dsound->device->buflen : 0) +
677 dsb->primary_mixpos - writepos;
679 ((dsb->dsound->device->mixpos < writepos) ? dsb->dsound->device->buflen : 0) +
680 dsb->dsound->device->mixpos - writepos;
682 ((buf_writepos < dsb->playpos) ? dsb->buflen : 0) +
683 buf_writepos - dsb->playpos;
684 DWORD buf_left = dsb->buflen - buf_writepos;
687 TRACE("(%p,%ld,%ld,%ld)\n",dsb,playpos,writepos,mixlen);
688 TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
689 TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
690 TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
692 TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
694 /* check for notification positions */
695 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
696 dsb->state != STATE_STARTING) {
697 DSOUND_CheckEvent(dsb, played);
700 /* save write position for non-GETCURRENTPOSITION2... */
701 dsb->playpos = buf_writepos;
703 /* check whether CalcPlayPosition detected a mixing underrun */
704 if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
705 /* it did, but did we have more to play? */
706 if ((dsb->playflags & DSBPLAY_LOOPING) ||
707 (dsb->buf_mixpos < dsb->buflen)) {
708 /* yes, have to recover */
709 ERR("underrun on sound buffer %p\n", dsb);
710 TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
712 dsb->primary_mixpos = writepos;
715 /* determine how far ahead we should mix */
716 if (((dsb->playflags & DSBPLAY_LOOPING) ||
717 (dsb->leadin && (dsb->probably_valid_to != 0))) &&
718 !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
719 /* if this is a streaming buffer, it typically means that
720 * we should defer mixing past probably_valid_to as long
721 * as we can, to avoid unnecessary remixing */
722 /* the heavy-looking calculations shouldn't be that bad,
723 * as any game isn't likely to be have more than 1 or 2
724 * streaming buffers in use at any time anyway... */
725 DWORD probably_valid_left =
726 (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
727 ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
728 dsb->probably_valid_to - buf_writepos;
729 /* check for leadin condition */
730 if ((probably_valid_left == 0) &&
731 (dsb->probably_valid_to == dsb->startpos) &&
733 probably_valid_left = dsb->buflen;
734 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
735 dsb->probably_valid_to, probably_valid_left);
736 /* check whether the app's time is already up */
737 if (probably_valid_left < dsb->writelead) {
738 WARN("probably_valid_to now within writelead, possible streaming underrun\n");
739 /* once we pass the point of no return,
740 * no reason to hold back anymore */
741 dsb->probably_valid_to = (DWORD)-1;
742 /* we just have to go ahead and mix what we have,
743 * there's no telling what the app is thinking anyway */
745 /* adjust for our frequency and our sample size */
746 probably_valid_left = MulDiv(probably_valid_left,
747 1 << DSOUND_FREQSHIFT,
748 dsb->pwfx->nBlockAlign * dsb->freqAdjust) *
749 dsb->dsound->device->pwfx->nBlockAlign;
750 /* check whether to clip mix_len */
751 if (probably_valid_left < mixlen) {
752 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
753 mixlen = probably_valid_left;
757 /* cut mixlen with what's already been mixed */
758 if (mixlen < primary_done) {
759 /* huh? and still CalcPlayPosition didn't
760 * detect an underrun? */
761 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
764 len = mixlen - primary_done;
765 TRACE("remaining mixlen=%ld\n", len);
767 if (len < dsb->dsound->device->fraglen) {
768 /* smaller than a fragment, wait until it gets larger
769 * before we take the mixing overhead */
770 TRACE("mixlen not worth it, deferring mixing\n");
775 /* ok, we know how much to mix, let's go */
776 still_behind = (adv_done > primary_done);
778 slen = dsb->dsound->device->buflen - dsb->primary_mixpos;
779 if (slen > len) slen = len;
780 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
782 if ((dsb->primary_mixpos < dsb->dsound->device->mixpos) &&
783 (dsb->primary_mixpos + slen >= dsb->dsound->device->mixpos))
784 still_behind = FALSE;
786 dsb->primary_mixpos += slen; len -= slen;
787 dsb->primary_mixpos %= dsb->dsound->device->buflen;
789 if ((dsb->state == STATE_STOPPED) || !slen) break;
791 TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->device->mixpos);
792 TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
795 /* check if buffer should be considered complete */
796 if (buf_left < dsb->writelead &&
797 !(dsb->playflags & DSBPLAY_LOOPING)) {
798 dsb->state = STATE_STOPPED;
800 dsb->last_playpos = 0;
803 dsb->need_remix = FALSE;
804 DSOUND_CheckEvent(dsb, buf_left);
807 /* return how far we think the primary buffer can
808 * advance its underrun detector...*/
809 if (still_behind) return 0;
810 if ((mixlen - len) < primary_done) return 0;
811 slen = ((dsb->primary_mixpos < dsb->dsound->device->mixpos) ?
812 dsb->dsound->device->buflen : 0) + dsb->primary_mixpos -
813 dsb->dsound->device->mixpos;
815 /* the primary_done and still_behind checks above should have worked */
816 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
822 static DWORD DSOUND_MixToPrimary(DirectSoundDevice *device, DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
824 INT i, len, maxlen = 0;
825 IDirectSoundBufferImpl *dsb;
827 TRACE("(%ld,%ld,%ld,%d)\n", playpos, writepos, mixlen, recover);
828 for (i = 0; i < device->nrofbuffers; i++) {
829 dsb = device->buffers[i];
831 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
832 TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
833 EnterCriticalSection(&(dsb->lock));
834 if (dsb->state == STATE_STOPPING) {
835 DSOUND_MixCancel(dsb, writepos, TRUE);
836 dsb->state = STATE_STOPPED;
837 DSOUND_CheckEvent(dsb, 0);
839 if ((dsb->state == STATE_STARTING) || recover) {
840 dsb->primary_mixpos = writepos;
841 dsb->cvolpan = dsb->volpan;
842 dsb->need_remix = FALSE;
844 else if (dsb->need_remix) {
845 DSOUND_MixCancel(dsb, writepos, TRUE);
846 dsb->cvolpan = dsb->volpan;
847 dsb->need_remix = FALSE;
849 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
850 if (dsb->state == STATE_STARTING)
851 dsb->state = STATE_PLAYING;
852 maxlen = (len > maxlen) ? len : maxlen;
854 LeaveCriticalSection(&(dsb->lock));
861 static void DSOUND_MixReset(DirectSoundDevice *device, DWORD writepos)
864 IDirectSoundBufferImpl *dsb;
867 TRACE("(%p,%ld)\n", device, writepos);
869 /* the sound of silence */
870 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
872 /* reset all buffer mix positions */
873 for (i = 0; i < device->nrofbuffers; i++) {
874 dsb = device->buffers[i];
876 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
877 TRACE("Resetting %p\n", dsb);
878 EnterCriticalSection(&(dsb->lock));
879 if (dsb->state == STATE_STOPPING) {
880 dsb->state = STATE_STOPPED;
882 else if (dsb->state == STATE_STARTING) {
885 DSOUND_MixCancel(dsb, writepos, FALSE);
886 dsb->cvolpan = dsb->volpan;
887 dsb->need_remix = FALSE;
889 LeaveCriticalSection(&(dsb->lock));
893 /* wipe out premixed data */
894 if (device->mixpos < writepos) {
895 FillMemory(device->buffer + writepos, device->buflen - writepos, nfiller);
896 FillMemory(device->buffer, device->mixpos, nfiller);
898 FillMemory(device->buffer + writepos, device->mixpos - writepos, nfiller);
901 /* reset primary mix position */
902 device->mixpos = writepos;
905 static void DSOUND_CheckReset(DirectSoundDevice *device, DWORD writepos)
907 TRACE("(%p,%ld)\n",device,writepos);
908 if (device->need_remix) {
909 DSOUND_MixReset(device, writepos);
910 device->need_remix = FALSE;
911 /* maximize Half-Life performance */
912 device->prebuf = ds_snd_queue_min;
913 device->precount = 0;
916 if (device->precount >= 4) {
917 if (device->prebuf < ds_snd_queue_max)
919 device->precount = 0;
922 TRACE("premix adjust: %d\n", device->prebuf);
925 void DSOUND_WaveQueue(DirectSoundDevice *device, DWORD mixq)
927 TRACE("(%p,%ld)\n", device, mixq);
928 if (mixq + device->pwqueue > ds_hel_queue) mixq = ds_hel_queue - device->pwqueue;
929 TRACE("queueing %ld buffers, starting at %d\n", mixq, device->pwwrite);
930 for (; mixq; mixq--) {
931 waveOutWrite(device->hwo, device->pwave[device->pwwrite], sizeof(WAVEHDR));
933 if (device->pwwrite >= DS_HEL_FRAGS) device->pwwrite = 0;
938 /* #define SYNC_CALLBACK */
940 void DSOUND_PerformMix(DirectSoundDevice *device)
946 TRACE("(%p)\n", device);
948 /* the sound of silence */
949 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
951 /* whether the primary is forced to play even without secondary buffers */
952 forced = ((device->state == STATE_PLAYING) || (device->state == STATE_STARTING));
954 if (device->priolevel != DSSCL_WRITEPRIMARY) {
955 BOOL paused = ((device->state == STATE_STOPPED) || (device->state == STATE_STARTING));
956 /* FIXME: document variables */
957 DWORD playpos, writepos, inq, maxq, frag;
959 hres = IDsDriverBuffer_GetPosition(device->hwbuf, &playpos, &writepos);
961 WARN("IDsDriverBuffer_GetPosition failed\n");
964 /* Well, we *could* do Just-In-Time mixing using the writepos,
965 * but that's a little bit ambitious and unnecessary... */
966 /* rather add our safety margin to the writepos, if we're playing */
968 writepos += device->writelead;
969 writepos %= device->buflen;
970 } else writepos = playpos;
972 playpos = device->pwplay * device->fraglen;
975 writepos += ds_hel_margin * device->fraglen;
976 writepos %= device->buflen;
979 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld, buflen=%ld\n",
980 playpos,writepos,device->playpos,device->mixpos,device->buflen);
981 assert(device->playpos < device->buflen);
982 /* wipe out just-played sound data */
983 if (playpos < device->playpos) {
984 FillMemory(device->buffer + device->playpos, device->buflen - device->playpos, nfiller);
985 FillMemory(device->buffer, playpos, nfiller);
987 FillMemory(device->buffer + device->playpos, playpos - device->playpos, nfiller);
989 device->playpos = playpos;
991 EnterCriticalSection(&(device->mixlock));
993 /* reset mixing if necessary */
994 DSOUND_CheckReset(device, writepos);
996 /* check how much prebuffering is left */
997 inq = device->mixpos;
999 inq += device->buflen;
1002 /* find the maximum we can prebuffer */
1005 if (maxq < writepos)
1006 maxq += device->buflen;
1008 } else maxq = device->buflen;
1010 /* clip maxq to device->prebuf */
1011 frag = device->prebuf * device->fraglen;
1012 if (maxq > frag) maxq = frag;
1014 /* check for consistency */
1016 /* the playback position must have passed our last
1017 * mixed position, i.e. it's an underrun, or we have
1018 * nothing more to play */
1019 TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
1021 /* stop the playback now, to allow buffers to refill */
1022 if (device->state == STATE_PLAYING) {
1023 device->state = STATE_STARTING;
1025 else if (device->state == STATE_STOPPING) {
1026 device->state = STATE_STOPPED;
1029 /* how can we have an underrun if we aren't playing? */
1030 WARN("unexpected primary state (%ld)\n", device->state);
1032 #ifdef SYNC_CALLBACK
1033 /* DSOUND_callback may need this lock */
1034 LeaveCriticalSection(&(device->mixlock));
1036 if (DSOUND_PrimaryStop(device) != DS_OK)
1037 WARN("DSOUND_PrimaryStop failed\n");
1038 #ifdef SYNC_CALLBACK
1039 EnterCriticalSection(&(device->mixlock));
1041 if (device->hwbuf) {
1042 /* the Stop is supposed to reset play position to beginning of buffer */
1043 /* unfortunately, OSS is not able to do so, so get current pointer */
1044 hres = IDsDriverBuffer_GetPosition(device->hwbuf, &playpos, NULL);
1046 LeaveCriticalSection(&(device->mixlock));
1047 WARN("IDsDriverBuffer_GetPosition failed\n");
1051 playpos = device->pwplay * device->fraglen;
1054 device->playpos = playpos;
1055 device->mixpos = writepos;
1057 maxq = device->buflen;
1058 if (maxq > frag) maxq = frag;
1059 FillMemory(device->buffer, device->buflen, nfiller);
1064 frag = DSOUND_MixToPrimary(device, playpos, writepos, maxq, paused);
1065 if (forced) frag = maxq - inq;
1066 device->mixpos += frag;
1067 device->mixpos %= device->buflen;
1070 /* buffers have been filled, restart playback */
1071 if (device->state == STATE_STARTING) {
1072 device->state = STATE_PLAYING;
1074 else if (device->state == STATE_STOPPED) {
1075 /* the dsound is supposed to play if there's something to play
1076 * even if it is reported as stopped, so don't let this confuse you */
1077 device->state = STATE_STOPPING;
1079 LeaveCriticalSection(&(device->mixlock));
1081 if (DSOUND_PrimaryPlay(device) != DS_OK)
1082 WARN("DSOUND_PrimaryPlay failed\n");
1084 TRACE("starting playback\n");
1088 LeaveCriticalSection(&(device->mixlock));
1090 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
1091 if (device->state == STATE_STARTING) {
1092 if (DSOUND_PrimaryPlay(device) != DS_OK)
1093 WARN("DSOUND_PrimaryPlay failed\n");
1095 device->state = STATE_PLAYING;
1097 else if (device->state == STATE_STOPPING) {
1098 if (DSOUND_PrimaryStop(device) != DS_OK)
1099 WARN("DSOUND_PrimaryStop failed\n");
1101 device->state = STATE_STOPPED;
1106 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1108 DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
1109 DWORD start_time = GetTickCount();
1111 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
1112 TRACE("entering at %ld\n", start_time);
1114 if (DSOUND_renderer[device->drvdesc.dnDevNode] != device) {
1115 ERR("dsound died without killing us?\n");
1116 timeKillEvent(timerID);
1117 timeEndPeriod(DS_TIME_RES);
1121 RtlAcquireResourceShared(&(device->buffer_list_lock), TRUE);
1124 DSOUND_PerformMix(device);
1126 RtlReleaseResource(&(device->buffer_list_lock));
1128 end_time = GetTickCount();
1129 TRACE("completed processing at %ld, duration = %ld\n", end_time, end_time - start_time);
1132 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1134 DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
1135 TRACE("(%p,%x,%lx,%lx,%lx)\n",hwo,msg,dwUser,dw1,dw2);
1136 TRACE("entering at %ld, msg=%08x(%s)\n", GetTickCount(), msg,
1137 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
1138 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1139 if (msg == MM_WOM_DONE) {
1140 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
1141 if (device->pwqueue == (DWORD)-1) {
1142 TRACE("completed due to reset\n");
1145 /* it could be a bad idea to enter critical section here... if there's lock contention,
1146 * the resulting scheduling delays might obstruct the winmm player thread */
1147 #ifdef SYNC_CALLBACK
1148 EnterCriticalSection(&(device->mixlock));
1150 /* retrieve current values */
1151 fraglen = device->fraglen;
1152 buflen = device->buflen;
1153 pwplay = device->pwplay;
1154 playpos = pwplay * fraglen;
1155 mixpos = device->mixpos;
1156 /* check remaining mixed data */
1157 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1158 mixq = inq / fraglen;
1159 if ((inq - (mixq * fraglen)) > 0) mixq++;
1160 /* complete the playing buffer */
1161 TRACE("done playing primary pos=%ld\n", playpos);
1163 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1164 /* write new values */
1165 device->pwplay = pwplay;
1167 /* queue new buffer if we have data for it */
1168 if (inq>1) DSOUND_WaveQueue(device, inq-1);
1169 #ifdef SYNC_CALLBACK
1170 LeaveCriticalSection(&(device->mixlock));
1173 TRACE("completed\n");