Changed Adam Sacarny's email, and -debugmsg to --debugmsg.
[wine/gsoc_dplay.git] / dlls / dsound / mixer.c
blob4f21f58ce9932b3d04b92c539b852df3da6e736c
1 /* DirectSound
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
22 #include "config.h"
23 #include <assert.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <sys/fcntl.h>
28 #ifdef HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif
31 #include <stdlib.h>
32 #include <string.h>
33 #include <math.h> /* Insomnia - pow() function */
35 #include "windef.h"
36 #include "winbase.h"
37 #include "wingdi.h"
38 #include "winuser.h"
39 #include "winerror.h"
40 #include "mmsystem.h"
41 #include "winreg.h"
42 #include "winternl.h"
43 #include "mmddk.h"
44 #include "wine/windef16.h"
45 #include "wine/debug.h"
46 #include "dsound.h"
47 #include "dsdriver.h"
48 #include "dsound_private.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
52 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
54 double temp;
55 TRACE("(%p)\n",volpan);
57 /* the AmpFactors are expressed in 16.16 fixed point */
58 volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
59 /* FIXME: dwPan{Left|Right}AmpFactor */
61 /* FIXME: use calculated vol and pan ampfactors */
62 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
63 volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
64 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
65 volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
67 TRACE("left = %lx, right = %lx\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
70 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
72 DWORD sw;
73 TRACE("(%p)\n",dsb);
75 sw = dsb->wfx.nChannels * (dsb->wfx.wBitsPerSample / 8);
76 /* calculate the 10ms write lead */
77 dsb->writelead = (dsb->freq / 100) * sw;
80 void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len)
82 int i;
83 DWORD offset;
84 LPDSBPOSITIONNOTIFY event;
85 TRACE("(%p,%d)\n",dsb,len);
87 if (dsb->nrofnotifies == 0)
88 return;
90 TRACE("(%p) buflen = %ld, playpos = %ld, len = %d\n",
91 dsb, dsb->buflen, dsb->playpos, len);
92 for (i = 0; i < dsb->nrofnotifies ; i++) {
93 event = dsb->notifies + i;
94 offset = event->dwOffset;
95 TRACE("checking %d, position %ld, event = %p\n",
96 i, offset, event->hEventNotify);
97 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
98 /* OK. [Inside DirectX, p274] */
99 /* */
100 /* This also means we can't sort the entries by offset, */
101 /* because DSBPN_OFFSETSTOP == -1 */
102 if (offset == DSBPN_OFFSETSTOP) {
103 if (dsb->state == STATE_STOPPED) {
104 SetEvent(event->hEventNotify);
105 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
106 return;
107 } else
108 return;
110 if ((dsb->playpos + len) >= dsb->buflen) {
111 if ((offset < ((dsb->playpos + len) % dsb->buflen)) ||
112 (offset >= dsb->playpos)) {
113 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
114 SetEvent(event->hEventNotify);
116 } else {
117 if ((offset >= dsb->playpos) && (offset < (dsb->playpos + len))) {
118 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
119 SetEvent(event->hEventNotify);
125 /* WAV format info can be found at:
127 * http://www.cwi.nl/ftp/audio/AudioFormats.part2
128 * ftp://ftp.cwi.nl/pub/audio/RIFF-format
130 * Import points to remember:
131 * 8-bit WAV is unsigned
132 * 16-bit WAV is signed
134 /* Use the same formulas as pcmconverter.c */
135 static inline INT16 cvtU8toS16(BYTE b)
137 return (short)((b+(b << 8))-32768);
140 static inline BYTE cvtS16toU8(INT16 s)
142 return (s >> 8) ^ (unsigned char)0x80;
145 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, BYTE *ibuf, BYTE *obuf )
147 INT fl,fr;
149 if (dsb->wfx.wBitsPerSample == 8) {
150 if (dsound->wfx.wBitsPerSample == 8 &&
151 dsound->wfx.nChannels == dsb->wfx.nChannels) {
152 /* avoid needless 8->16->8 conversion */
153 *obuf=*ibuf;
154 if (dsb->wfx.nChannels==2)
155 *(obuf+1)=*(ibuf+1);
156 return;
158 fl = cvtU8toS16(*ibuf);
159 fr = (dsb->wfx.nChannels==2 ? cvtU8toS16(*(ibuf + 1)) : fl);
160 } else {
161 fl = *((INT16 *)ibuf);
162 fr = (dsb->wfx.nChannels==2 ? *(((INT16 *)ibuf) + 1) : fl);
165 if (dsound->wfx.nChannels == 2) {
166 if (dsound->wfx.wBitsPerSample == 8) {
167 *obuf = cvtS16toU8(fl);
168 *(obuf + 1) = cvtS16toU8(fr);
169 return;
171 if (dsound->wfx.wBitsPerSample == 16) {
172 *((INT16 *)obuf) = fl;
173 *(((INT16 *)obuf) + 1) = fr;
174 return;
177 if (dsound->wfx.nChannels == 1) {
178 fl = (fl + fr) >> 1;
179 if (dsound->wfx.wBitsPerSample == 8) {
180 *obuf = cvtS16toU8(fl);
181 return;
183 if (dsound->wfx.wBitsPerSample == 16) {
184 *((INT16 *)obuf) = fl;
185 return;
190 /* Now with PerfectPitch (tm) technology */
191 static INT DSOUND_MixerNorm(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
193 INT i, size, ipos, ilen;
194 BYTE *ibp, *obp;
195 INT iAdvance = dsb->wfx.nBlockAlign;
196 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
198 ibp = dsb->buffer->memory + dsb->buf_mixpos;
199 obp = buf;
201 TRACE("(%p, %p, %p), buf_mixpos=%ld\n", dsb, ibp, obp, dsb->buf_mixpos);
202 /* Check for the best case */
203 if ((dsb->freq == dsb->dsound->wfx.nSamplesPerSec) &&
204 (dsb->wfx.wBitsPerSample == dsb->dsound->wfx.wBitsPerSample) &&
205 (dsb->wfx.nChannels == dsb->dsound->wfx.nChannels)) {
206 DWORD bytesleft = dsb->buflen - dsb->buf_mixpos;
207 TRACE("(%p) Best case\n", dsb);
208 if (len <= bytesleft )
209 memcpy(obp, ibp, len);
210 else { /* wrap */
211 memcpy(obp, ibp, bytesleft );
212 memcpy(obp + bytesleft, dsb->buffer->memory, len - bytesleft);
214 return len;
217 /* Check for same sample rate */
218 if (dsb->freq == dsb->dsound->wfx.nSamplesPerSec) {
219 TRACE("(%p) Same sample rate %ld = primary %ld\n", dsb,
220 dsb->freq, dsb->dsound->wfx.nSamplesPerSec);
221 ilen = 0;
222 for (i = 0; i < len; i += oAdvance) {
223 cp_fields(dsb, ibp, obp );
224 ibp += iAdvance;
225 ilen += iAdvance;
226 obp += oAdvance;
227 if (ibp >= (BYTE *)(dsb->buffer->memory + dsb->buflen))
228 ibp = dsb->buffer->memory; /* wrap */
230 return (ilen);
233 /* Mix in different sample rates */
234 /* */
235 /* New PerfectPitch(tm) Technology (c) 1998 Rob Riggs */
236 /* Patent Pending :-] */
238 /* Patent enhancements (c) 2000 Ove KÃ¥ven,
239 * TransGaming Technologies Inc. */
241 /* FIXME("(%p) Adjusting frequency: %ld -> %ld (need optimization)\n",
242 dsb, dsb->freq, dsb->dsound->wfx.nSamplesPerSec); */
244 size = len / oAdvance;
245 ilen = 0;
246 ipos = dsb->buf_mixpos;
247 for (i = 0; i < size; i++) {
248 cp_fields(dsb, (dsb->buffer->memory + ipos), obp);
249 obp += oAdvance;
250 dsb->freqAcc += dsb->freqAdjust;
251 if (dsb->freqAcc >= (1<<DSOUND_FREQSHIFT)) {
252 ULONG adv = (dsb->freqAcc>>DSOUND_FREQSHIFT) * iAdvance;
253 dsb->freqAcc &= (1<<DSOUND_FREQSHIFT)-1;
254 ipos += adv; ilen += adv;
255 while (ipos >= dsb->buflen)
256 ipos -= dsb->buflen;
259 return ilen;
262 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
264 INT i;
265 BYTE *bpc = buf;
266 INT16 *bps = (INT16 *) buf;
268 TRACE("(%p,%p,%d)\n",dsb,buf,len);
269 TRACE("left = %lx, right = %lx\n", dsb->cvolpan.dwTotalLeftAmpFactor,
270 dsb->cvolpan.dwTotalRightAmpFactor);
272 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->cvolpan.lPan == 0)) &&
273 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->cvolpan.lVolume == 0)) &&
274 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
275 return; /* Nothing to do */
277 /* If we end up with some bozo coder using panning or 3D sound */
278 /* with a mono primary buffer, it could sound very weird using */
279 /* this method. Oh well, tough patooties. */
281 switch (dsb->dsound->wfx.wBitsPerSample) {
282 case 8:
283 /* 8-bit WAV is unsigned, but we need to operate */
284 /* on signed data for this to work properly */
285 switch (dsb->dsound->wfx.nChannels) {
286 case 1:
287 for (i = 0; i < len; i++) {
288 INT val = *bpc - 128;
289 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
290 *bpc = val + 128;
291 bpc++;
293 break;
294 case 2:
295 for (i = 0; i < len; i+=2) {
296 INT val = *bpc - 128;
297 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
298 *bpc++ = val + 128;
299 val = *bpc - 128;
300 val = (val * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
301 *bpc = val + 128;
302 bpc++;
304 break;
305 default:
306 FIXME("doesn't support %d channels\n", dsb->dsound->wfx.nChannels);
307 break;
309 break;
310 case 16:
311 /* 16-bit WAV is signed -- much better */
312 switch (dsb->dsound->wfx.nChannels) {
313 case 1:
314 for (i = 0; i < len; i += 2) {
315 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
316 bps++;
318 break;
319 case 2:
320 for (i = 0; i < len; i += 4) {
321 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
322 bps++;
323 *bps = (*bps * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
324 bps++;
326 break;
327 default:
328 FIXME("doesn't support %d channels\n", dsb->dsound->wfx.nChannels);
329 break;
331 break;
332 default:
333 FIXME("doesn't support %d bit samples\n", dsb->dsound->wfx.wBitsPerSample);
334 break;
338 static void *tmp_buffer;
339 static size_t tmp_buffer_len = 0;
341 static void *DSOUND_tmpbuffer(size_t len)
343 if (len>tmp_buffer_len) {
344 void *new_buffer = realloc(tmp_buffer, len);
345 if (new_buffer) {
346 tmp_buffer = new_buffer;
347 tmp_buffer_len = len;
349 return new_buffer;
351 return tmp_buffer;
354 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
356 INT i, len, ilen, temp, field, nBlockAlign;
357 INT advance = dsb->dsound->wfx.wBitsPerSample >> 3;
358 BYTE *buf, *ibuf, *obuf;
359 INT16 *ibufs, *obufs;
361 TRACE("(%p,%ld,%ld)\n",dsb,writepos,fraglen);
363 len = fraglen;
364 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
365 temp = MulDiv(dsb->dsound->wfx.nAvgBytesPerSec, dsb->buflen,
366 dsb->nAvgBytesPerSec) -
367 MulDiv(dsb->dsound->wfx.nAvgBytesPerSec, dsb->buf_mixpos,
368 dsb->nAvgBytesPerSec);
369 len = (len > temp) ? temp : len;
371 nBlockAlign = dsb->dsound->wfx.nBlockAlign;
372 len = len / nBlockAlign * nBlockAlign; /* data alignment */
374 if (len == 0) {
375 /* This should only happen if we aren't looping and temp < nBlockAlign */
376 return 0;
379 /* Been seeing segfaults in malloc() for some reason... */
380 TRACE("allocating buffer (size = %d)\n", len);
381 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
382 return 0;
384 TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
386 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
387 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
388 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
389 (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
390 DSOUND_MixerVol(dsb, ibuf, len);
392 obuf = dsb->dsound->buffer + writepos;
393 for (i = 0; i < len; i += advance) {
394 obufs = (INT16 *) obuf;
395 ibufs = (INT16 *) ibuf;
396 if (dsb->dsound->wfx.wBitsPerSample == 8) {
397 /* 8-bit WAV is unsigned */
398 field = (*ibuf - 128);
399 field += (*obuf - 128);
400 field = field > 127 ? 127 : field;
401 field = field < -128 ? -128 : field;
402 *obuf = field + 128;
403 } else {
404 /* 16-bit WAV is signed */
405 field = *ibufs;
406 field += *obufs;
407 field = field > 32767 ? 32767 : field;
408 field = field < -32768 ? -32768 : field;
409 *obufs = field;
411 ibuf += advance;
412 obuf += advance;
413 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
414 obuf = dsb->dsound->buffer;
416 /* free(buf); */
418 if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
419 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
420 * not the MIX position... but if the sound buffer is bigger than our prebuffering
421 * (which must be the case for the streaming buffers that need this hack anyway)
422 * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
423 dsb->leadin = FALSE;
426 dsb->buf_mixpos += ilen;
428 if (dsb->buf_mixpos >= dsb->buflen) {
429 if (dsb->playflags & DSBPLAY_LOOPING) {
430 /* wrap */
431 while (dsb->buf_mixpos >= dsb->buflen)
432 dsb->buf_mixpos -= dsb->buflen;
433 if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
434 dsb->leadin = FALSE; /* HACK: see above */
438 return len;
441 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
443 INT i, ilen, field, nBlockAlign;
444 INT advance = dsb->dsound->wfx.wBitsPerSample >> 3;
445 BYTE *buf, *ibuf, *obuf;
446 INT16 *ibufs, *obufs;
447 TRACE("(%p,%ld,%ld)\n",dsb,writepos,len);
449 nBlockAlign = dsb->dsound->wfx.nBlockAlign;
450 len = len / nBlockAlign * nBlockAlign; /* data alignment */
452 TRACE("allocating buffer (size = %ld)\n", len);
453 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
454 return;
456 TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
458 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
459 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
460 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
461 (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
462 DSOUND_MixerVol(dsb, ibuf, len);
464 /* subtract instead of add, to phase out premixed data */
465 obuf = dsb->dsound->buffer + writepos;
466 for (i = 0; i < len; i += advance) {
467 obufs = (INT16 *) obuf;
468 ibufs = (INT16 *) ibuf;
469 if (dsb->dsound->wfx.wBitsPerSample == 8) {
470 /* 8-bit WAV is unsigned */
471 field = (*ibuf - 128);
472 field -= (*obuf - 128);
473 field = field > 127 ? 127 : field;
474 field = field < -128 ? -128 : field;
475 *obuf = field + 128;
476 } else {
477 /* 16-bit WAV is signed */
478 field = *ibufs;
479 field -= *obufs;
480 field = field > 32767 ? 32767 : field;
481 field = field < -32768 ? -32768 : field;
482 *obufs = field;
484 ibuf += advance;
485 obuf += advance;
486 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
487 obuf = dsb->dsound->buffer;
489 /* free(buf); */
492 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
494 DWORD size, flen, len, npos, nlen;
495 INT iAdvance = dsb->wfx.nBlockAlign;
496 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
497 /* determine amount of premixed data to cancel */
498 DWORD primary_done =
499 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
500 dsb->primary_mixpos - writepos;
502 TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
504 /* backtrack the mix position */
505 size = primary_done / oAdvance;
506 flen = size * dsb->freqAdjust;
507 len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
508 flen &= (1<<DSOUND_FREQSHIFT)-1;
509 while (dsb->freqAcc < flen) {
510 len += iAdvance;
511 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
513 len %= dsb->buflen;
514 npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
515 dsb->buf_mixpos - len;
516 if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
517 /* stop backtracking at startpos */
518 npos = dsb->startpos;
519 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
520 dsb->buf_mixpos - npos;
521 flen = dsb->freqAcc;
522 nlen = len / dsb->wfx.nBlockAlign;
523 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
524 nlen *= dsb->dsound->wfx.nBlockAlign;
525 writepos =
526 ((dsb->primary_mixpos < nlen) ? dsb->dsound->buflen : 0) +
527 dsb->primary_mixpos - nlen;
530 dsb->freqAcc -= flen;
531 dsb->buf_mixpos = npos;
532 dsb->primary_mixpos = writepos;
534 TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
535 dsb->buf_mixpos, dsb->primary_mixpos, len);
537 if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
540 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
542 #if 0
543 DWORD i, size, flen, len, npos, nlen;
544 INT iAdvance = dsb->wfx.nBlockAlign;
545 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
546 /* determine amount of premixed data to cancel */
547 DWORD buf_done =
548 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
549 dsb->buf_mixpos - buf_writepos;
550 #endif
552 WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
553 /* since this is not implemented yet, just cancel *ALL* prebuffering for now
554 * (which is faster anyway when there's only a single secondary buffer) */
555 dsb->dsound->need_remix = TRUE;
558 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
560 TRACE("(%p)\n",dsb);
561 EnterCriticalSection(&dsb->lock);
562 if (dsb->state == STATE_PLAYING) {
563 #if 0 /* this may not be quite reliable yet */
564 dsb->need_remix = TRUE;
565 #else
566 dsb->dsound->need_remix = TRUE;
567 #endif
569 LeaveCriticalSection(&dsb->lock);
572 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
574 DWORD len, slen;
575 /* determine this buffer's write position */
576 DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, dsb->state & dsb->dsound->state, writepos,
577 writepos, dsb->primary_mixpos, dsb->buf_mixpos);
578 /* determine how much already-mixed data exists */
579 DWORD buf_done =
580 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
581 dsb->buf_mixpos - buf_writepos;
582 DWORD primary_done =
583 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
584 dsb->primary_mixpos - writepos;
585 DWORD adv_done =
586 ((dsb->dsound->mixpos < writepos) ? dsb->dsound->buflen : 0) +
587 dsb->dsound->mixpos - writepos;
588 DWORD played =
589 ((buf_writepos < dsb->playpos) ? dsb->buflen : 0) +
590 buf_writepos - dsb->playpos;
591 DWORD buf_left = dsb->buflen - buf_writepos;
592 int still_behind;
594 TRACE("(%p,%ld,%ld,%ld)\n",dsb,playpos,writepos,mixlen);
595 TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
596 TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
597 TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
598 mixlen);
599 TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
601 /* check for notification positions */
602 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
603 dsb->state != STATE_STARTING) {
604 DSOUND_CheckEvent(dsb, played);
607 /* save write position for non-GETCURRENTPOSITION2... */
608 dsb->playpos = buf_writepos;
610 /* check whether CalcPlayPosition detected a mixing underrun */
611 if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
612 /* it did, but did we have more to play? */
613 if ((dsb->playflags & DSBPLAY_LOOPING) ||
614 (dsb->buf_mixpos < dsb->buflen)) {
615 /* yes, have to recover */
616 ERR("underrun on sound buffer %p\n", dsb);
617 TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
619 dsb->primary_mixpos = writepos;
620 primary_done = 0;
622 /* determine how far ahead we should mix */
623 if (((dsb->playflags & DSBPLAY_LOOPING) ||
624 (dsb->leadin && (dsb->probably_valid_to != 0))) &&
625 !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
626 /* if this is a streaming buffer, it typically means that
627 * we should defer mixing past probably_valid_to as long
628 * as we can, to avoid unnecessary remixing */
629 /* the heavy-looking calculations shouldn't be that bad,
630 * as any game isn't likely to be have more than 1 or 2
631 * streaming buffers in use at any time anyway... */
632 DWORD probably_valid_left =
633 (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
634 ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
635 dsb->probably_valid_to - buf_writepos;
636 /* check for leadin condition */
637 if ((probably_valid_left == 0) &&
638 (dsb->probably_valid_to == dsb->startpos) &&
639 dsb->leadin)
640 probably_valid_left = dsb->buflen;
641 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
642 dsb->probably_valid_to, probably_valid_left);
643 /* check whether the app's time is already up */
644 if (probably_valid_left < dsb->writelead) {
645 WARN("probably_valid_to now within writelead, possible streaming underrun\n");
646 /* once we pass the point of no return,
647 * no reason to hold back anymore */
648 dsb->probably_valid_to = (DWORD)-1;
649 /* we just have to go ahead and mix what we have,
650 * there's no telling what the app is thinking anyway */
651 } else {
652 /* adjust for our frequency and our sample size */
653 probably_valid_left = MulDiv(probably_valid_left,
654 1 << DSOUND_FREQSHIFT,
655 dsb->wfx.nBlockAlign * dsb->freqAdjust) *
656 dsb->dsound->wfx.nBlockAlign;
657 /* check whether to clip mix_len */
658 if (probably_valid_left < mixlen) {
659 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
660 mixlen = probably_valid_left;
664 /* cut mixlen with what's already been mixed */
665 if (mixlen < primary_done) {
666 /* huh? and still CalcPlayPosition didn't
667 * detect an underrun? */
668 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
669 return 0;
671 len = mixlen - primary_done;
672 TRACE("remaining mixlen=%ld\n", len);
674 if (len < dsb->dsound->fraglen) {
675 /* smaller than a fragment, wait until it gets larger
676 * before we take the mixing overhead */
677 TRACE("mixlen not worth it, deferring mixing\n");
678 still_behind = 1;
679 goto post_mix;
682 /* ok, we know how much to mix, let's go */
683 still_behind = (adv_done > primary_done);
684 while (len) {
685 slen = dsb->dsound->buflen - dsb->primary_mixpos;
686 if (slen > len) slen = len;
687 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
689 if ((dsb->primary_mixpos < dsb->dsound->mixpos) &&
690 (dsb->primary_mixpos + slen >= dsb->dsound->mixpos))
691 still_behind = FALSE;
693 dsb->primary_mixpos += slen; len -= slen;
694 while (dsb->primary_mixpos >= dsb->dsound->buflen)
695 dsb->primary_mixpos -= dsb->dsound->buflen;
697 if ((dsb->state == STATE_STOPPED) || !slen) break;
699 TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->mixpos);
700 TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
702 post_mix:
703 /* check if buffer should be considered complete */
704 if (buf_left < dsb->writelead &&
705 !(dsb->playflags & DSBPLAY_LOOPING)) {
706 dsb->state = STATE_STOPPED;
707 dsb->playpos = 0;
708 dsb->last_playpos = 0;
709 dsb->buf_mixpos = 0;
710 dsb->leadin = FALSE;
711 DSOUND_CheckEvent(dsb, buf_left);
714 /* return how far we think the primary buffer can
715 * advance its underrun detector...*/
716 if (still_behind) return 0;
717 if ((mixlen - len) < primary_done) return 0;
718 slen = ((dsb->primary_mixpos < dsb->dsound->mixpos) ?
719 dsb->dsound->buflen : 0) + dsb->primary_mixpos -
720 dsb->dsound->mixpos;
721 if (slen > mixlen) {
722 /* the primary_done and still_behind checks above should have worked */
723 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
724 slen = 0;
726 return slen;
729 static DWORD DSOUND_MixToPrimary(DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
731 INT i, len, maxlen = 0;
732 IDirectSoundBufferImpl *dsb;
734 TRACE("(%ld,%ld,%ld,%d)\n", playpos, writepos, mixlen, recover);
735 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
736 dsb = dsound->buffers[i];
738 if (!dsb || !dsb->lpVtbl)
739 continue;
740 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
741 TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
742 EnterCriticalSection(&(dsb->lock));
743 if (dsb->state == STATE_STOPPING) {
744 DSOUND_MixCancel(dsb, writepos, TRUE);
745 dsb->state = STATE_STOPPED;
746 DSOUND_CheckEvent(dsb, 0);
747 } else {
748 if ((dsb->state == STATE_STARTING) || recover) {
749 dsb->primary_mixpos = writepos;
750 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
751 dsb->need_remix = FALSE;
753 else if (dsb->need_remix) {
754 DSOUND_MixCancel(dsb, writepos, TRUE);
755 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
756 dsb->need_remix = FALSE;
758 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
759 if (dsb->state == STATE_STARTING)
760 dsb->state = STATE_PLAYING;
761 maxlen = (len > maxlen) ? len : maxlen;
763 LeaveCriticalSection(&(dsb->lock));
767 return maxlen;
770 static void DSOUND_MixReset(DWORD writepos)
772 INT i;
773 IDirectSoundBufferImpl *dsb;
774 int nfiller;
776 TRACE("(%ld)\n", writepos);
778 /* the sound of silence */
779 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
781 /* reset all buffer mix positions */
782 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
783 dsb = dsound->buffers[i];
785 if (!dsb || !dsb->lpVtbl)
786 continue;
787 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
788 TRACE("Resetting %p\n", dsb);
789 EnterCriticalSection(&(dsb->lock));
790 if (dsb->state == STATE_STOPPING) {
791 dsb->state = STATE_STOPPED;
793 else if (dsb->state == STATE_STARTING) {
794 /* nothing */
795 } else {
796 DSOUND_MixCancel(dsb, writepos, FALSE);
797 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
798 dsb->need_remix = FALSE;
800 LeaveCriticalSection(&(dsb->lock));
804 /* wipe out premixed data */
805 if (dsound->mixpos < writepos) {
806 memset(dsound->buffer + writepos, nfiller, dsound->buflen - writepos);
807 memset(dsound->buffer, nfiller, dsound->mixpos);
808 } else {
809 memset(dsound->buffer + writepos, nfiller, dsound->mixpos - writepos);
812 /* reset primary mix position */
813 dsound->mixpos = writepos;
816 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
818 TRACE("(%p,%ld)\n",dsound,writepos);
819 if (dsound->need_remix) {
820 DSOUND_MixReset(writepos);
821 dsound->need_remix = FALSE;
822 /* maximize Half-Life performance */
823 dsound->prebuf = ds_snd_queue_min;
824 dsound->precount = 0;
825 } else {
826 dsound->precount++;
827 if (dsound->precount >= 4) {
828 if (dsound->prebuf < ds_snd_queue_max)
829 dsound->prebuf++;
830 dsound->precount = 0;
833 TRACE("premix adjust: %d\n", dsound->prebuf);
836 void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
838 TRACE("(%p,%ld)\n",dsound,mixq);
839 if (mixq + dsound->pwqueue > ds_hel_queue) mixq = ds_hel_queue - dsound->pwqueue;
840 TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
841 for (; mixq; mixq--) {
842 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
843 dsound->pwwrite++;
844 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
845 dsound->pwqueue++;
849 /* #define SYNC_CALLBACK */
851 void DSOUND_PerformMix(void)
853 int nfiller;
854 BOOL forced;
855 HRESULT hres;
857 TRACE("()\n");
859 /* the sound of silence */
860 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
862 /* whether the primary is forced to play even without secondary buffers */
863 forced = ((dsound->state == STATE_PLAYING) || (dsound->state == STATE_STARTING));
865 if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
866 BOOL paused = ((dsound->state == STATE_STOPPED) || (dsound->state == STATE_STARTING));
867 /* FIXME: document variables */
868 DWORD playpos, writepos, inq, maxq, frag;
869 if (dsound->hwbuf) {
870 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, &writepos);
871 if (hres) {
872 WARN("IDsDriverBuffer_GetPosition failed\n");
873 return;
875 /* Well, we *could* do Just-In-Time mixing using the writepos,
876 * but that's a little bit ambitious and unnecessary... */
877 /* rather add our safety margin to the writepos, if we're playing */
878 if (!paused) {
879 writepos += dsound->writelead;
880 while (writepos >= dsound->buflen)
881 writepos -= dsound->buflen;
882 } else writepos = playpos;
883 } else {
884 playpos = dsound->pwplay * dsound->fraglen;
885 writepos = playpos;
886 if (!paused) {
887 writepos += ds_hel_margin * dsound->fraglen;
888 while (writepos >= dsound->buflen)
889 writepos -= dsound->buflen;
892 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld, buflen=%ld\n",
893 playpos,writepos,dsound->playpos,dsound->mixpos,dsound->buflen);
894 assert(dsound->playpos < dsound->buflen);
895 /* wipe out just-played sound data */
896 if (playpos < dsound->playpos) {
897 memset(dsound->buffer + dsound->playpos, nfiller, dsound->buflen - dsound->playpos);
898 memset(dsound->buffer, nfiller, playpos);
899 } else {
900 memset(dsound->buffer + dsound->playpos, nfiller, playpos - dsound->playpos);
902 dsound->playpos = playpos;
904 EnterCriticalSection(&(dsound->mixlock));
906 /* reset mixing if necessary */
907 DSOUND_CheckReset(dsound, writepos);
909 /* check how much prebuffering is left */
910 inq = dsound->mixpos;
911 if (inq < writepos)
912 inq += dsound->buflen;
913 inq -= writepos;
915 /* find the maximum we can prebuffer */
916 if (!paused) {
917 maxq = playpos;
918 if (maxq < writepos)
919 maxq += dsound->buflen;
920 maxq -= writepos;
921 } else maxq = dsound->buflen;
923 /* clip maxq to dsound->prebuf */
924 frag = dsound->prebuf * dsound->fraglen;
925 if (maxq > frag) maxq = frag;
927 /* check for consistency */
928 if (inq > maxq) {
929 /* the playback position must have passed our last
930 * mixed position, i.e. it's an underrun, or we have
931 * nothing more to play */
932 TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
933 inq = 0;
934 /* stop the playback now, to allow buffers to refill */
935 if (dsound->state == STATE_PLAYING) {
936 dsound->state = STATE_STARTING;
938 else if (dsound->state == STATE_STOPPING) {
939 dsound->state = STATE_STOPPED;
941 else {
942 /* how can we have an underrun if we aren't playing? */
943 WARN("unexpected primary state (%ld)\n", dsound->state);
945 #ifdef SYNC_CALLBACK
946 /* DSOUND_callback may need this lock */
947 LeaveCriticalSection(&(dsound->mixlock));
948 #endif
949 if (DSOUND_PrimaryStop(dsound) != DS_OK)
950 WARN("DSOUND_PrimaryStop failed\n");
951 #ifdef SYNC_CALLBACK
952 EnterCriticalSection(&(dsound->mixlock));
953 #endif
954 if (dsound->hwbuf) {
955 /* the Stop is supposed to reset play position to beginning of buffer */
956 /* unfortunately, OSS is not able to do so, so get current pointer */
957 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, NULL);
958 if (hres) {
959 LeaveCriticalSection(&(dsound->mixlock));
960 WARN("IDsDriverBuffer_GetPosition failed\n");
961 return;
963 } else {
964 playpos = dsound->pwplay * dsound->fraglen;
966 writepos = playpos;
967 dsound->playpos = playpos;
968 dsound->mixpos = writepos;
969 inq = 0;
970 maxq = dsound->buflen;
971 if (maxq > frag) maxq = frag;
972 memset(dsound->buffer, nfiller, dsound->buflen);
973 paused = TRUE;
976 /* do the mixing */
977 frag = DSOUND_MixToPrimary(playpos, writepos, maxq, paused);
978 if (forced) frag = maxq - inq;
979 dsound->mixpos += frag;
980 while (dsound->mixpos >= dsound->buflen)
981 dsound->mixpos -= dsound->buflen;
983 if (frag) {
984 /* buffers have been filled, restart playback */
985 if (dsound->state == STATE_STARTING) {
986 dsound->state = STATE_PLAYING;
988 else if (dsound->state == STATE_STOPPED) {
989 /* the dsound is supposed to play if there's something to play
990 * even if it is reported as stopped, so don't let this confuse you */
991 dsound->state = STATE_STOPPING;
993 LeaveCriticalSection(&(dsound->mixlock));
994 if (paused) {
995 if (DSOUND_PrimaryPlay(dsound) != DS_OK)
996 WARN("DSOUND_PrimaryPlay failed\n");
997 else
998 TRACE("starting playback\n");
1001 else
1002 LeaveCriticalSection(&(dsound->mixlock));
1003 } else {
1004 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
1005 if (dsound->state == STATE_STARTING) {
1006 if (DSOUND_PrimaryPlay(dsound) != DS_OK)
1007 WARN("DSOUND_PrimaryPlay failed\n");
1008 else
1009 dsound->state = STATE_PLAYING;
1011 else if (dsound->state == STATE_STOPPING) {
1012 if (DSOUND_PrimaryStop(dsound) != DS_OK)
1013 WARN("DSOUND_PrimaryStop failed\n");
1014 else
1015 dsound->state = STATE_STOPPED;
1020 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1022 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
1023 TRACE("entering at %ld\n", GetTickCount());
1025 if (!dsound) {
1026 ERR("dsound died without killing us?\n");
1027 timeKillEvent(timerID);
1028 timeEndPeriod(DS_TIME_RES);
1029 return;
1032 RtlAcquireResourceShared(&(dsound->lock), TRUE);
1034 if (dsound->ref) {
1035 DSOUND_PerformMix();
1038 RtlReleaseResource(&(dsound->lock));
1040 TRACE("completed processing at %ld\n", GetTickCount());
1043 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1045 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1046 TRACE("(%p,%x,%lx,%lx,%lx)\n",hwo,msg,dwUser,dw1,dw2);
1047 TRACE("entering at %ld, msg=%08x(%s)\n", GetTickCount(), msg,
1048 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
1049 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1050 if (msg == MM_WOM_DONE) {
1051 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
1052 if (This->pwqueue == (DWORD)-1) {
1053 TRACE("completed due to reset\n");
1054 return;
1056 /* it could be a bad idea to enter critical section here... if there's lock contention,
1057 * the resulting scheduling delays might obstruct the winmm player thread */
1058 #ifdef SYNC_CALLBACK
1059 EnterCriticalSection(&(This->mixlock));
1060 #endif
1061 /* retrieve current values */
1062 fraglen = dsound->fraglen;
1063 buflen = dsound->buflen;
1064 pwplay = dsound->pwplay;
1065 playpos = pwplay * fraglen;
1066 mixpos = dsound->mixpos;
1067 /* check remaining mixed data */
1068 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1069 mixq = inq / fraglen;
1070 if ((inq - (mixq * fraglen)) > 0) mixq++;
1071 /* complete the playing buffer */
1072 TRACE("done playing primary pos=%ld\n", playpos);
1073 pwplay++;
1074 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1075 /* write new values */
1076 dsound->pwplay = pwplay;
1077 dsound->pwqueue--;
1078 /* queue new buffer if we have data for it */
1079 if (inq>1) DSOUND_WaveQueue(This, inq-1);
1080 #ifdef SYNC_CALLBACK
1081 LeaveCriticalSection(&(This->mixlock));
1082 #endif
1084 TRACE("completed\n");