Added YUV routines needed for v4l driver, and in the future possibly
[wine/gsoc-2012-control.git] / dlls / dsound / mixer.c
blob0aacf78412b3976535bad5641fe864b51f6dc254
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 <assert.h>
23 #include <stdarg.h>
24 #include <math.h> /* Insomnia - pow() function */
26 #define NONAMELESSSTRUCT
27 #define NONAMELESSUNION
28 #include "windef.h"
29 #include "winbase.h"
30 #include "mmsystem.h"
31 #include "winreg.h"
32 #include "winternl.h"
33 #include "wine/debug.h"
34 #include "dsound.h"
35 #include "dsdriver.h"
36 #include "dsound_private.h"
38 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
40 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
42 double temp;
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)
61 double left,right;
62 TRACE("(%p)\n",volpan);
64 TRACE("left=%lx, right=%lx\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
65 if (volpan->dwTotalLeftAmpFactor==0)
66 left=-10000;
67 else
68 left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
69 if (volpan->dwTotalRightAmpFactor==0)
70 right=-10000;
71 else
72 right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
73 if (left<right)
75 volpan->lVolume=right;
76 volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
78 else
80 volpan->lVolume=left;
81 volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
83 if (volpan->lVolume < -10000)
84 volpan->lVolume=-10000;
85 volpan->lPan=right-left;
86 if (volpan->lPan < -10000)
87 volpan->lPan=-10000;
89 TRACE("Vol=%ld Pan=%ld\n", volpan->lVolume, volpan->lPan);
92 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
94 TRACE("(%p)\n",dsb);
96 /* calculate the 10ms write lead */
97 dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
100 void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len)
102 int i;
103 DWORD offset;
104 LPDSBPOSITIONNOTIFY event;
105 TRACE("(%p,%d)\n",dsb,len);
107 if (dsb->nrofnotifies == 0)
108 return;
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] */
119 /* */
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);
126 return;
127 } else
128 return;
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);
136 } else {
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 INT fl,fr;
169 if (dsb->pwfx->wBitsPerSample == 8) {
170 if (dsb->dsound->pwfx->wBitsPerSample == 8 &&
171 dsb->dsound->pwfx->nChannels == dsb->pwfx->nChannels) {
172 /* avoid needless 8->16->8 conversion */
173 *obuf=*ibuf;
174 if (dsb->pwfx->nChannels==2)
175 *(obuf+1)=*(ibuf+1);
176 return;
178 fl = cvtU8toS16(*ibuf);
179 fr = (dsb->pwfx->nChannels==2 ? cvtU8toS16(*(ibuf + 1)) : fl);
180 } else {
181 fl = *((INT16 *)ibuf);
182 fr = (dsb->pwfx->nChannels==2 ? *(((INT16 *)ibuf) + 1) : fl);
185 if (dsb->dsound->pwfx->nChannels == 2) {
186 if (dsb->dsound->pwfx->wBitsPerSample == 8) {
187 *obuf = cvtS16toU8(fl);
188 *(obuf + 1) = cvtS16toU8(fr);
189 return;
191 if (dsb->dsound->pwfx->wBitsPerSample == 16) {
192 *((INT16 *)obuf) = fl;
193 *(((INT16 *)obuf) + 1) = fr;
194 return;
197 if (dsb->dsound->pwfx->nChannels == 1) {
198 fl = (fl + fr) >> 1;
199 if (dsb->dsound->pwfx->wBitsPerSample == 8) {
200 *obuf = cvtS16toU8(fl);
201 return;
203 if (dsb->dsound->pwfx->wBitsPerSample == 16) {
204 *((INT16 *)obuf) = fl;
205 return;
210 /* Now with PerfectPitch (tm) technology */
211 static INT DSOUND_MixerNorm(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
213 INT i, size, ipos, ilen;
214 BYTE *ibp, *obp;
215 INT iAdvance = dsb->pwfx->nBlockAlign;
216 INT oAdvance = dsb->dsound->pwfx->nBlockAlign;
218 ibp = dsb->buffer->memory + dsb->buf_mixpos;
219 obp = buf;
221 TRACE("(%p, %p, %p), buf_mixpos=%ld\n", dsb, ibp, obp, dsb->buf_mixpos);
222 /* Check for the best case */
223 if ((dsb->freq == dsb->dsound->pwfx->nSamplesPerSec) &&
224 (dsb->pwfx->wBitsPerSample == dsb->dsound->pwfx->wBitsPerSample) &&
225 (dsb->pwfx->nChannels == dsb->dsound->pwfx->nChannels)) {
226 INT bytesleft = dsb->buflen - dsb->buf_mixpos;
227 TRACE("(%p) Best case\n", dsb);
228 if (len <= bytesleft )
229 CopyMemory(obp, ibp, len);
230 else { /* wrap */
231 CopyMemory(obp, ibp, bytesleft);
232 CopyMemory(obp + bytesleft, dsb->buffer->memory, len - bytesleft);
234 return len;
237 /* Check for same sample rate */
238 if (dsb->freq == dsb->dsound->pwfx->nSamplesPerSec) {
239 TRACE("(%p) Same sample rate %ld = primary %ld\n", dsb,
240 dsb->freq, dsb->dsound->pwfx->nSamplesPerSec);
241 ilen = 0;
242 for (i = 0; i < len; i += oAdvance) {
243 cp_fields(dsb, ibp, obp );
244 ibp += iAdvance;
245 ilen += iAdvance;
246 obp += oAdvance;
247 if (ibp >= (BYTE *)(dsb->buffer->memory + dsb->buflen))
248 ibp = dsb->buffer->memory; /* wrap */
250 return (ilen);
253 /* Mix in different sample rates */
254 /* */
255 /* New PerfectPitch(tm) Technology (c) 1998 Rob Riggs */
256 /* Patent Pending :-] */
258 /* Patent enhancements (c) 2000 Ove KÃ¥ven,
259 * TransGaming Technologies Inc. */
261 /* FIXME("(%p) Adjusting frequency: %ld -> %ld (need optimization)\n",
262 dsb, dsb->freq, dsb->dsound->pwfx->nSamplesPerSec); */
264 size = len / oAdvance;
265 ilen = 0;
266 ipos = dsb->buf_mixpos;
267 for (i = 0; i < size; i++) {
268 cp_fields(dsb, (dsb->buffer->memory + ipos), obp);
269 obp += oAdvance;
270 dsb->freqAcc += dsb->freqAdjust;
271 if (dsb->freqAcc >= (1<<DSOUND_FREQSHIFT)) {
272 ULONG adv = (dsb->freqAcc>>DSOUND_FREQSHIFT) * iAdvance;
273 dsb->freqAcc &= (1<<DSOUND_FREQSHIFT)-1;
274 ipos += adv; ilen += adv;
275 ipos %= dsb->buflen;
278 return ilen;
281 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
283 INT i;
284 BYTE *bpc = buf;
285 INT16 *bps = (INT16 *) buf;
287 TRACE("(%p,%p,%d)\n",dsb,buf,len);
288 TRACE("left = %lx, right = %lx\n", dsb->cvolpan.dwTotalLeftAmpFactor,
289 dsb->cvolpan.dwTotalRightAmpFactor);
291 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->cvolpan.lPan == 0)) &&
292 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->cvolpan.lVolume == 0)) &&
293 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
294 return; /* Nothing to do */
296 /* If we end up with some bozo coder using panning or 3D sound */
297 /* with a mono primary buffer, it could sound very weird using */
298 /* this method. Oh well, tough patooties. */
300 switch (dsb->dsound->pwfx->wBitsPerSample) {
301 case 8:
302 /* 8-bit WAV is unsigned, but we need to operate */
303 /* on signed data for this to work properly */
304 switch (dsb->dsound->pwfx->nChannels) {
305 case 1:
306 for (i = 0; i < len; i++) {
307 INT val = *bpc - 128;
308 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
309 *bpc = val + 128;
310 bpc++;
312 break;
313 case 2:
314 for (i = 0; i < len; i+=2) {
315 INT val = *bpc - 128;
316 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
317 *bpc++ = val + 128;
318 val = *bpc - 128;
319 val = (val * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
320 *bpc = val + 128;
321 bpc++;
323 break;
324 default:
325 FIXME("doesn't support %d channels\n", dsb->dsound->pwfx->nChannels);
326 break;
328 break;
329 case 16:
330 /* 16-bit WAV is signed -- much better */
331 switch (dsb->dsound->pwfx->nChannels) {
332 case 1:
333 for (i = 0; i < len; i += 2) {
334 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
335 bps++;
337 break;
338 case 2:
339 for (i = 0; i < len; i += 4) {
340 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
341 bps++;
342 *bps = (*bps * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
343 bps++;
345 break;
346 default:
347 FIXME("doesn't support %d channels\n", dsb->dsound->pwfx->nChannels);
348 break;
350 break;
351 default:
352 FIXME("doesn't support %d bit samples\n", dsb->dsound->pwfx->wBitsPerSample);
353 break;
357 static LPBYTE DSOUND_tmpbuffer(IDirectSoundImpl *dsound, DWORD len)
359 TRACE("(%p,%ld)\n",dsound,len);
361 if (len > dsound->tmp_buffer_len) {
362 if (dsound->tmp_buffer)
363 dsound->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsound->tmp_buffer, len);
364 else
365 dsound->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
367 dsound->tmp_buffer_len = len;
370 return dsound->tmp_buffer;
373 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
375 INT i, len, ilen, field, todo;
376 BYTE *buf, *ibuf;
378 TRACE("(%p,%ld,%ld)\n",dsb,writepos,fraglen);
380 len = fraglen;
381 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
382 INT temp = MulDiv(dsb->dsound->pwfx->nAvgBytesPerSec, dsb->buflen,
383 dsb->nAvgBytesPerSec) -
384 MulDiv(dsb->dsound->pwfx->nAvgBytesPerSec, dsb->buf_mixpos,
385 dsb->nAvgBytesPerSec);
386 len = min(len, temp);
389 if (len % dsb->dsound->pwfx->nBlockAlign) {
390 INT nBlockAlign = dsb->dsound->pwfx->nBlockAlign;
391 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
392 len = (len / nBlockAlign) * nBlockAlign; /* data alignment */
395 if (len == 0) {
396 /* This should only happen if we aren't looping and temp < nBlockAlign */
397 return 0;
400 if ((buf = ibuf = DSOUND_tmpbuffer(dsb->dsound, len)) == NULL)
401 return 0;
403 TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
405 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
406 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
407 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
408 (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
409 DSOUND_MixerVol(dsb, ibuf, len);
411 if (dsb->dsound->pwfx->wBitsPerSample == 8) {
412 BYTE *obuf = dsb->dsound->buffer + writepos;
414 if ((writepos + len) <= dsb->dsound->buflen)
415 todo = len;
416 else
417 todo = dsb->dsound->buflen - writepos;
419 for (i = 0; i < todo; i++) {
420 /* 8-bit WAV is unsigned */
421 field = (*ibuf++ - 128);
422 field += (*obuf - 128);
423 if (field > 127) field = 127;
424 else if (field < -128) field = -128;
425 *obuf++ = field + 128;
428 if (todo < len) {
429 todo = len - todo;
430 obuf = dsb->dsound->buffer;
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;
441 } else {
442 INT16 *ibufs, *obufs;
444 ibufs = (INT16 *) ibuf;
445 obufs = (INT16 *)(dsb->dsound->buffer + writepos);
447 if ((writepos + len) <= dsb->dsound->buflen)
448 todo = len / 2;
449 else
450 todo = (dsb->dsound->buflen - writepos) / 2;
452 for (i = 0; i < todo; i++) {
453 /* 16-bit WAV is signed */
454 field = *ibufs++;
455 field += *obufs;
456 if (field > 32767) field = 32767;
457 else if (field < -32768) field = -32768;
458 *obufs++ = field;
461 if (todo < (len / 2)) {
462 todo = (len / 2) - todo;
463 obufs = (INT16 *)dsb->dsound->buffer;
465 for (i = 0; i < todo; i++) {
466 /* 16-bit WAV is signed */
467 field = *ibufs++;
468 field += *obufs;
469 if (field > 32767) field = 32767;
470 else if (field < -32768) field = -32768;
471 *obufs++ = field;
476 if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
477 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
478 * not the MIX position... but if the sound buffer is bigger than our prebuffering
479 * (which must be the case for the streaming buffers that need this hack anyway)
480 * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
481 dsb->leadin = FALSE;
484 dsb->buf_mixpos += ilen;
486 if (dsb->buf_mixpos >= dsb->buflen) {
487 if (dsb->playflags & DSBPLAY_LOOPING) {
488 /* wrap */
489 dsb->buf_mixpos %= dsb->buflen;
490 if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
491 dsb->leadin = FALSE; /* HACK: see above */
495 return len;
498 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
500 INT ilen, field;
501 UINT i, todo;
502 BYTE *buf, *ibuf;
504 TRACE("(%p,%ld,%ld)\n",dsb,writepos,len);
506 if (len % dsb->dsound->pwfx->nBlockAlign) {
507 INT nBlockAlign = dsb->dsound->pwfx->nBlockAlign;
508 ERR("length not a multiple of block size, len = %ld, block size = %d\n", len, nBlockAlign);
509 len = (len / nBlockAlign) * nBlockAlign; /* data alignment */
512 if ((buf = ibuf = DSOUND_tmpbuffer(dsb->dsound, len)) == NULL)
513 return;
515 TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
517 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
518 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
519 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
520 (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
521 DSOUND_MixerVol(dsb, ibuf, len);
523 /* subtract instead of add, to phase out premixed data */
524 if (dsb->dsound->pwfx->wBitsPerSample == 8) {
525 BYTE *obuf = dsb->dsound->buffer + writepos;
527 if ((writepos + len) <= dsb->dsound->buflen)
528 todo = len;
529 else
530 todo = dsb->dsound->buflen - writepos;
532 for (i = 0; i < todo; i++) {
533 /* 8-bit WAV is unsigned */
534 field = (*ibuf++ - 128);
535 field -= (*obuf - 128);
536 if (field > 127) field = 127;
537 else if (field < -128) field = -128;
538 *obuf++ = field + 128;
541 if (todo < len) {
542 todo = len - todo;
543 obuf = dsb->dsound->buffer;
545 for (i = 0; i < todo; i++) {
546 /* 8-bit WAV is unsigned */
547 field = (*ibuf++ - 128);
548 field -= (*obuf - 128);
549 if (field > 127) field = 127;
550 else if (field < -128) field = -128;
551 *obuf++ = field + 128;
554 } else {
555 INT16 *ibufs, *obufs;
557 ibufs = (INT16 *) ibuf;
558 obufs = (INT16 *)(dsb->dsound->buffer + writepos);
560 if ((writepos + len) <= dsb->dsound->buflen)
561 todo = len / 2;
562 else
563 todo = (dsb->dsound->buflen - writepos) / 2;
565 for (i = 0; i < todo; i++) {
566 /* 16-bit WAV is signed */
567 field = *ibufs++;
568 field -= *obufs;
569 if (field > 32767) field = 32767;
570 else if (field < -32768) field = -32768;
571 *obufs++ = field;
574 if (todo < (len / 2)) {
575 todo = (len / 2) - todo;
576 obufs = (INT16 *)dsb->dsound->buffer;
578 for (i = 0; i < todo; i++) {
579 /* 16-bit WAV is signed */
580 field = *ibufs++;
581 field -= *obufs;
582 if (field > 32767) field = 32767;
583 else if (field < -32768) field = -32768;
584 *obufs++ = field;
590 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
592 DWORD size, flen, len, npos, nlen;
593 INT iAdvance = dsb->pwfx->nBlockAlign;
594 INT oAdvance = dsb->dsound->pwfx->nBlockAlign;
595 /* determine amount of premixed data to cancel */
596 DWORD primary_done =
597 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
598 dsb->primary_mixpos - writepos;
600 TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
602 /* backtrack the mix position */
603 size = primary_done / oAdvance;
604 flen = size * dsb->freqAdjust;
605 len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
606 flen &= (1<<DSOUND_FREQSHIFT)-1;
607 while (dsb->freqAcc < flen) {
608 len += iAdvance;
609 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
611 len %= dsb->buflen;
612 npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
613 dsb->buf_mixpos - len;
614 if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
615 /* stop backtracking at startpos */
616 npos = dsb->startpos;
617 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
618 dsb->buf_mixpos - npos;
619 flen = dsb->freqAcc;
620 nlen = len / dsb->pwfx->nBlockAlign;
621 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
622 nlen *= dsb->dsound->pwfx->nBlockAlign;
623 writepos =
624 ((dsb->primary_mixpos < nlen) ? dsb->dsound->buflen : 0) +
625 dsb->primary_mixpos - nlen;
628 dsb->freqAcc -= flen;
629 dsb->buf_mixpos = npos;
630 dsb->primary_mixpos = writepos;
632 TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
633 dsb->buf_mixpos, dsb->primary_mixpos, len);
635 if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
638 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
640 #if 0
641 DWORD i, size, flen, len, npos, nlen;
642 INT iAdvance = dsb->pwfx->nBlockAlign;
643 INT oAdvance = dsb->dsound->pwfx->nBlockAlign;
644 /* determine amount of premixed data to cancel */
645 DWORD buf_done =
646 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
647 dsb->buf_mixpos - buf_writepos;
648 #endif
650 WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
651 /* since this is not implemented yet, just cancel *ALL* prebuffering for now
652 * (which is faster anyway when there's only a single secondary buffer) */
653 dsb->dsound->need_remix = TRUE;
656 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
658 TRACE("(%p)\n",dsb);
659 EnterCriticalSection(&dsb->lock);
660 if (dsb->state == STATE_PLAYING)
661 dsb->dsound->need_remix = TRUE;
662 LeaveCriticalSection(&dsb->lock);
665 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
667 DWORD len, slen;
668 /* determine this buffer's write position */
669 DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, writepos, writepos);
670 /* determine how much already-mixed data exists */
671 DWORD buf_done =
672 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
673 dsb->buf_mixpos - buf_writepos;
674 DWORD primary_done =
675 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
676 dsb->primary_mixpos - writepos;
677 DWORD adv_done =
678 ((dsb->dsound->mixpos < writepos) ? dsb->dsound->buflen : 0) +
679 dsb->dsound->mixpos - writepos;
680 DWORD played =
681 ((buf_writepos < dsb->playpos) ? dsb->buflen : 0) +
682 buf_writepos - dsb->playpos;
683 DWORD buf_left = dsb->buflen - buf_writepos;
684 int still_behind;
686 TRACE("(%p,%ld,%ld,%ld)\n",dsb,playpos,writepos,mixlen);
687 TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
688 TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
689 TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
690 mixlen);
691 TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
693 /* check for notification positions */
694 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
695 dsb->state != STATE_STARTING) {
696 DSOUND_CheckEvent(dsb, played);
699 /* save write position for non-GETCURRENTPOSITION2... */
700 dsb->playpos = buf_writepos;
702 /* check whether CalcPlayPosition detected a mixing underrun */
703 if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
704 /* it did, but did we have more to play? */
705 if ((dsb->playflags & DSBPLAY_LOOPING) ||
706 (dsb->buf_mixpos < dsb->buflen)) {
707 /* yes, have to recover */
708 ERR("underrun on sound buffer %p\n", dsb);
709 TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
711 dsb->primary_mixpos = writepos;
712 primary_done = 0;
714 /* determine how far ahead we should mix */
715 if (((dsb->playflags & DSBPLAY_LOOPING) ||
716 (dsb->leadin && (dsb->probably_valid_to != 0))) &&
717 !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
718 /* if this is a streaming buffer, it typically means that
719 * we should defer mixing past probably_valid_to as long
720 * as we can, to avoid unnecessary remixing */
721 /* the heavy-looking calculations shouldn't be that bad,
722 * as any game isn't likely to be have more than 1 or 2
723 * streaming buffers in use at any time anyway... */
724 DWORD probably_valid_left =
725 (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
726 ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
727 dsb->probably_valid_to - buf_writepos;
728 /* check for leadin condition */
729 if ((probably_valid_left == 0) &&
730 (dsb->probably_valid_to == dsb->startpos) &&
731 dsb->leadin)
732 probably_valid_left = dsb->buflen;
733 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
734 dsb->probably_valid_to, probably_valid_left);
735 /* check whether the app's time is already up */
736 if (probably_valid_left < dsb->writelead) {
737 WARN("probably_valid_to now within writelead, possible streaming underrun\n");
738 /* once we pass the point of no return,
739 * no reason to hold back anymore */
740 dsb->probably_valid_to = (DWORD)-1;
741 /* we just have to go ahead and mix what we have,
742 * there's no telling what the app is thinking anyway */
743 } else {
744 /* adjust for our frequency and our sample size */
745 probably_valid_left = MulDiv(probably_valid_left,
746 1 << DSOUND_FREQSHIFT,
747 dsb->pwfx->nBlockAlign * dsb->freqAdjust) *
748 dsb->dsound->pwfx->nBlockAlign;
749 /* check whether to clip mix_len */
750 if (probably_valid_left < mixlen) {
751 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
752 mixlen = probably_valid_left;
756 /* cut mixlen with what's already been mixed */
757 if (mixlen < primary_done) {
758 /* huh? and still CalcPlayPosition didn't
759 * detect an underrun? */
760 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
761 return 0;
763 len = mixlen - primary_done;
764 TRACE("remaining mixlen=%ld\n", len);
766 if (len < dsb->dsound->fraglen) {
767 /* smaller than a fragment, wait until it gets larger
768 * before we take the mixing overhead */
769 TRACE("mixlen not worth it, deferring mixing\n");
770 still_behind = 1;
771 goto post_mix;
774 /* ok, we know how much to mix, let's go */
775 still_behind = (adv_done > primary_done);
776 while (len) {
777 slen = dsb->dsound->buflen - dsb->primary_mixpos;
778 if (slen > len) slen = len;
779 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
781 if ((dsb->primary_mixpos < dsb->dsound->mixpos) &&
782 (dsb->primary_mixpos + slen >= dsb->dsound->mixpos))
783 still_behind = FALSE;
785 dsb->primary_mixpos += slen; len -= slen;
786 dsb->primary_mixpos %= dsb->dsound->buflen;
788 if ((dsb->state == STATE_STOPPED) || !slen) break;
790 TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->mixpos);
791 TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
793 post_mix:
794 /* check if buffer should be considered complete */
795 if (buf_left < dsb->writelead &&
796 !(dsb->playflags & DSBPLAY_LOOPING)) {
797 dsb->state = STATE_STOPPED;
798 dsb->playpos = 0;
799 dsb->last_playpos = 0;
800 dsb->buf_mixpos = 0;
801 dsb->leadin = FALSE;
802 dsb->need_remix = FALSE;
803 DSOUND_CheckEvent(dsb, buf_left);
806 /* return how far we think the primary buffer can
807 * advance its underrun detector...*/
808 if (still_behind) return 0;
809 if ((mixlen - len) < primary_done) return 0;
810 slen = ((dsb->primary_mixpos < dsb->dsound->mixpos) ?
811 dsb->dsound->buflen : 0) + dsb->primary_mixpos -
812 dsb->dsound->mixpos;
813 if (slen > mixlen) {
814 /* the primary_done and still_behind checks above should have worked */
815 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
816 slen = 0;
818 return slen;
821 static DWORD DSOUND_MixToPrimary(IDirectSoundImpl *dsound, DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
823 INT i, len, maxlen = 0;
824 IDirectSoundBufferImpl *dsb;
826 TRACE("(%ld,%ld,%ld,%d)\n", playpos, writepos, mixlen, recover);
827 for (i = 0; i < dsound->nrofbuffers; i++) {
828 dsb = dsound->buffers[i];
830 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
831 TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
832 EnterCriticalSection(&(dsb->lock));
833 if (dsb->state == STATE_STOPPING) {
834 DSOUND_MixCancel(dsb, writepos, TRUE);
835 dsb->state = STATE_STOPPED;
836 DSOUND_CheckEvent(dsb, 0);
837 } else {
838 if ((dsb->state == STATE_STARTING) || recover) {
839 dsb->primary_mixpos = writepos;
840 dsb->cvolpan = dsb->volpan;
841 dsb->need_remix = FALSE;
843 else if (dsb->need_remix) {
844 DSOUND_MixCancel(dsb, writepos, TRUE);
845 dsb->cvolpan = dsb->volpan;
846 dsb->need_remix = FALSE;
848 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
849 if (dsb->state == STATE_STARTING)
850 dsb->state = STATE_PLAYING;
851 maxlen = (len > maxlen) ? len : maxlen;
853 LeaveCriticalSection(&(dsb->lock));
857 return maxlen;
860 static void DSOUND_MixReset(IDirectSoundImpl *dsound, DWORD writepos)
862 INT i;
863 IDirectSoundBufferImpl *dsb;
864 int nfiller;
866 TRACE("(%ld)\n", writepos);
868 /* the sound of silence */
869 nfiller = dsound->pwfx->wBitsPerSample == 8 ? 128 : 0;
871 /* reset all buffer mix positions */
872 for (i = 0; i < dsound->nrofbuffers; i++) {
873 dsb = dsound->buffers[i];
875 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
876 TRACE("Resetting %p\n", dsb);
877 EnterCriticalSection(&(dsb->lock));
878 if (dsb->state == STATE_STOPPING) {
879 dsb->state = STATE_STOPPED;
881 else if (dsb->state == STATE_STARTING) {
882 /* nothing */
883 } else {
884 DSOUND_MixCancel(dsb, writepos, FALSE);
885 dsb->cvolpan = dsb->volpan;
886 dsb->need_remix = FALSE;
888 LeaveCriticalSection(&(dsb->lock));
892 /* wipe out premixed data */
893 if (dsound->mixpos < writepos) {
894 FillMemory(dsound->buffer + writepos, dsound->buflen - writepos, nfiller);
895 FillMemory(dsound->buffer, dsound->mixpos, nfiller);
896 } else {
897 FillMemory(dsound->buffer + writepos, dsound->mixpos - writepos, nfiller);
900 /* reset primary mix position */
901 dsound->mixpos = writepos;
904 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
906 TRACE("(%p,%ld)\n",dsound,writepos);
907 if (dsound->need_remix) {
908 DSOUND_MixReset(dsound, writepos);
909 dsound->need_remix = FALSE;
910 /* maximize Half-Life performance */
911 dsound->prebuf = ds_snd_queue_min;
912 dsound->precount = 0;
913 } else {
914 dsound->precount++;
915 if (dsound->precount >= 4) {
916 if (dsound->prebuf < ds_snd_queue_max)
917 dsound->prebuf++;
918 dsound->precount = 0;
921 TRACE("premix adjust: %d\n", dsound->prebuf);
924 void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
926 TRACE("(%p,%ld)\n",dsound,mixq);
927 if (mixq + dsound->pwqueue > ds_hel_queue) mixq = ds_hel_queue - dsound->pwqueue;
928 TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
929 for (; mixq; mixq--) {
930 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
931 dsound->pwwrite++;
932 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
933 dsound->pwqueue++;
937 /* #define SYNC_CALLBACK */
939 void DSOUND_PerformMix(IDirectSoundImpl *dsound)
941 int nfiller;
942 BOOL forced;
943 HRESULT hres;
945 TRACE("(%p)\n", dsound);
947 /* the sound of silence */
948 nfiller = dsound->pwfx->wBitsPerSample == 8 ? 128 : 0;
950 /* whether the primary is forced to play even without secondary buffers */
951 forced = ((dsound->state == STATE_PLAYING) || (dsound->state == STATE_STARTING));
953 if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
954 BOOL paused = ((dsound->state == STATE_STOPPED) || (dsound->state == STATE_STARTING));
955 /* FIXME: document variables */
956 DWORD playpos, writepos, inq, maxq, frag;
957 if (dsound->hwbuf) {
958 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, &writepos);
959 if (hres) {
960 WARN("IDsDriverBuffer_GetPosition failed\n");
961 return;
963 /* Well, we *could* do Just-In-Time mixing using the writepos,
964 * but that's a little bit ambitious and unnecessary... */
965 /* rather add our safety margin to the writepos, if we're playing */
966 if (!paused) {
967 writepos += dsound->writelead;
968 writepos %= dsound->buflen;
969 } else writepos = playpos;
970 } else {
971 playpos = dsound->pwplay * dsound->fraglen;
972 writepos = playpos;
973 if (!paused) {
974 writepos += ds_hel_margin * dsound->fraglen;
975 writepos %= dsound->buflen;
978 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld, buflen=%ld\n",
979 playpos,writepos,dsound->playpos,dsound->mixpos,dsound->buflen);
980 assert(dsound->playpos < dsound->buflen);
981 /* wipe out just-played sound data */
982 if (playpos < dsound->playpos) {
983 FillMemory(dsound->buffer + dsound->playpos, dsound->buflen - dsound->playpos, nfiller);
984 FillMemory(dsound->buffer, playpos, nfiller);
985 } else {
986 FillMemory(dsound->buffer + dsound->playpos, playpos - dsound->playpos, nfiller);
988 dsound->playpos = playpos;
990 EnterCriticalSection(&(dsound->mixlock));
992 /* reset mixing if necessary */
993 DSOUND_CheckReset(dsound, writepos);
995 /* check how much prebuffering is left */
996 inq = dsound->mixpos;
997 if (inq < writepos)
998 inq += dsound->buflen;
999 inq -= writepos;
1001 /* find the maximum we can prebuffer */
1002 if (!paused) {
1003 maxq = playpos;
1004 if (maxq < writepos)
1005 maxq += dsound->buflen;
1006 maxq -= writepos;
1007 } else maxq = dsound->buflen;
1009 /* clip maxq to dsound->prebuf */
1010 frag = dsound->prebuf * dsound->fraglen;
1011 if (maxq > frag) maxq = frag;
1013 /* check for consistency */
1014 if (inq > maxq) {
1015 /* the playback position must have passed our last
1016 * mixed position, i.e. it's an underrun, or we have
1017 * nothing more to play */
1018 TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
1019 inq = 0;
1020 /* stop the playback now, to allow buffers to refill */
1021 if (dsound->state == STATE_PLAYING) {
1022 dsound->state = STATE_STARTING;
1024 else if (dsound->state == STATE_STOPPING) {
1025 dsound->state = STATE_STOPPED;
1027 else {
1028 /* how can we have an underrun if we aren't playing? */
1029 WARN("unexpected primary state (%ld)\n", dsound->state);
1031 #ifdef SYNC_CALLBACK
1032 /* DSOUND_callback may need this lock */
1033 LeaveCriticalSection(&(dsound->mixlock));
1034 #endif
1035 if (DSOUND_PrimaryStop(dsound) != DS_OK)
1036 WARN("DSOUND_PrimaryStop failed\n");
1037 #ifdef SYNC_CALLBACK
1038 EnterCriticalSection(&(dsound->mixlock));
1039 #endif
1040 if (dsound->hwbuf) {
1041 /* the Stop is supposed to reset play position to beginning of buffer */
1042 /* unfortunately, OSS is not able to do so, so get current pointer */
1043 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, NULL);
1044 if (hres) {
1045 LeaveCriticalSection(&(dsound->mixlock));
1046 WARN("IDsDriverBuffer_GetPosition failed\n");
1047 return;
1049 } else {
1050 playpos = dsound->pwplay * dsound->fraglen;
1052 writepos = playpos;
1053 dsound->playpos = playpos;
1054 dsound->mixpos = writepos;
1055 inq = 0;
1056 maxq = dsound->buflen;
1057 if (maxq > frag) maxq = frag;
1058 FillMemory(dsound->buffer, dsound->buflen, nfiller);
1059 paused = TRUE;
1062 /* do the mixing */
1063 frag = DSOUND_MixToPrimary(dsound, playpos, writepos, maxq, paused);
1064 if (forced) frag = maxq - inq;
1065 dsound->mixpos += frag;
1066 dsound->mixpos %= dsound->buflen;
1068 if (frag) {
1069 /* buffers have been filled, restart playback */
1070 if (dsound->state == STATE_STARTING) {
1071 dsound->state = STATE_PLAYING;
1073 else if (dsound->state == STATE_STOPPED) {
1074 /* the dsound is supposed to play if there's something to play
1075 * even if it is reported as stopped, so don't let this confuse you */
1076 dsound->state = STATE_STOPPING;
1078 LeaveCriticalSection(&(dsound->mixlock));
1079 if (paused) {
1080 if (DSOUND_PrimaryPlay(dsound) != DS_OK)
1081 WARN("DSOUND_PrimaryPlay failed\n");
1082 else
1083 TRACE("starting playback\n");
1086 else
1087 LeaveCriticalSection(&(dsound->mixlock));
1088 } else {
1089 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
1090 if (dsound->state == STATE_STARTING) {
1091 if (DSOUND_PrimaryPlay(dsound) != DS_OK)
1092 WARN("DSOUND_PrimaryPlay failed\n");
1093 else
1094 dsound->state = STATE_PLAYING;
1096 else if (dsound->state == STATE_STOPPING) {
1097 if (DSOUND_PrimaryStop(dsound) != DS_OK)
1098 WARN("DSOUND_PrimaryStop failed\n");
1099 else
1100 dsound->state = STATE_STOPPED;
1105 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1107 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1108 DWORD start_time = GetTickCount();
1109 DWORD end_time;
1110 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
1111 TRACE("entering at %ld\n", start_time);
1113 if (DSOUND_renderer != This) {
1114 ERR("dsound died without killing us?\n");
1115 timeKillEvent(timerID);
1116 timeEndPeriod(DS_TIME_RES);
1117 return;
1120 RtlAcquireResourceShared(&(This->buffer_list_lock), TRUE);
1122 if (This->ref)
1123 DSOUND_PerformMix(This);
1125 RtlReleaseResource(&(This->buffer_list_lock));
1127 end_time = GetTickCount();
1128 TRACE("completed processing at %ld, duration = %ld\n", end_time, end_time - start_time);
1131 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1133 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1134 TRACE("(%p,%x,%lx,%lx,%lx)\n",hwo,msg,dwUser,dw1,dw2);
1135 TRACE("entering at %ld, msg=%08x(%s)\n", GetTickCount(), msg,
1136 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
1137 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1138 if (msg == MM_WOM_DONE) {
1139 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
1140 if (This->pwqueue == (DWORD)-1) {
1141 TRACE("completed due to reset\n");
1142 return;
1144 /* it could be a bad idea to enter critical section here... if there's lock contention,
1145 * the resulting scheduling delays might obstruct the winmm player thread */
1146 #ifdef SYNC_CALLBACK
1147 EnterCriticalSection(&(This->mixlock));
1148 #endif
1149 /* retrieve current values */
1150 fraglen = This->fraglen;
1151 buflen = This->buflen;
1152 pwplay = This->pwplay;
1153 playpos = pwplay * fraglen;
1154 mixpos = This->mixpos;
1155 /* check remaining mixed data */
1156 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1157 mixq = inq / fraglen;
1158 if ((inq - (mixq * fraglen)) > 0) mixq++;
1159 /* complete the playing buffer */
1160 TRACE("done playing primary pos=%ld\n", playpos);
1161 pwplay++;
1162 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1163 /* write new values */
1164 This->pwplay = pwplay;
1165 This->pwqueue--;
1166 /* queue new buffer if we have data for it */
1167 if (inq>1) DSOUND_WaveQueue(This, inq-1);
1168 #ifdef SYNC_CALLBACK
1169 LeaveCriticalSection(&(This->mixlock));
1170 #endif
1172 TRACE("completed\n");