Add missing LeaveCriticalSection's in error path.
[wine/multimedia.git] / dlls / dsound / mixer.c
blobd2faa8b8a3307eb36aed3fc8a500c32af05709a2
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 <stdio.h>
25 #include <sys/types.h>
26 #include <sys/fcntl.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #include <stdlib.h>
31 #include <string.h>
32 #include <math.h> /* Insomnia - pow() function */
34 #include "windef.h"
35 #include "winbase.h"
36 #include "wingdi.h"
37 #include "winuser.h"
38 #include "winerror.h"
39 #include "mmsystem.h"
40 #include "winternl.h"
41 #include "mmddk.h"
42 #include "wine/windef16.h"
43 #include "wine/debug.h"
44 #include "dsound.h"
45 #include "dsdriver.h"
46 #include "dsound_private.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
50 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
52 double temp;
54 /* the AmpFactors are expressed in 16.16 fixed point */
55 volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 65536);
56 /* FIXME: dwPan{Left|Right}AmpFactor */
58 /* FIXME: use calculated vol and pan ampfactors */
59 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
60 volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 65536);
61 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
62 volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 65536);
64 TRACE("left = %lx, right = %lx\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
67 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
69 DWORD sw;
71 sw = dsb->wfx.nChannels * (dsb->wfx.wBitsPerSample / 8);
72 /* calculate the 10ms write lead */
73 dsb->writelead = (dsb->freq / 100) * sw;
76 void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len)
78 int i;
79 DWORD offset;
80 LPDSBPOSITIONNOTIFY event;
82 if (dsb->nrofnotifies == 0)
83 return;
85 TRACE("(%p) buflen = %ld, playpos = %ld, len = %d\n",
86 dsb, dsb->buflen, dsb->playpos, len);
87 for (i = 0; i < dsb->nrofnotifies ; i++) {
88 event = dsb->notifies + i;
89 offset = event->dwOffset;
90 TRACE("checking %d, position %ld, event = %p\n",
91 i, offset, event->hEventNotify);
92 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
93 /* OK. [Inside DirectX, p274] */
94 /* */
95 /* This also means we can't sort the entries by offset, */
96 /* because DSBPN_OFFSETSTOP == -1 */
97 if (offset == DSBPN_OFFSETSTOP) {
98 if (dsb->state == STATE_STOPPED) {
99 SetEvent(event->hEventNotify);
100 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
101 return;
102 } else
103 return;
105 if ((dsb->playpos + len) >= dsb->buflen) {
106 if ((offset < ((dsb->playpos + len) % dsb->buflen)) ||
107 (offset >= dsb->playpos)) {
108 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
109 SetEvent(event->hEventNotify);
111 } else {
112 if ((offset >= dsb->playpos) && (offset < (dsb->playpos + len))) {
113 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
114 SetEvent(event->hEventNotify);
120 /* WAV format info can be found at:
122 * http://www.cwi.nl/ftp/audio/AudioFormats.part2
123 * ftp://ftp.cwi.nl/pub/audio/RIFF-format
125 * Import points to remember:
126 * 8-bit WAV is unsigned
127 * 16-bit WAV is signed
129 /* Use the same formulas as pcmconverter.c */
130 static inline INT16 cvtU8toS16(BYTE b)
132 return (short)((b+(b << 8))-32768);
135 static inline BYTE cvtS16toU8(INT16 s)
137 return (s >> 8) ^ (unsigned char)0x80;
140 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, BYTE *ibuf, BYTE *obuf )
142 INT fl,fr;
144 if (dsb->wfx.wBitsPerSample == 8) {
145 if (dsound->wfx.wBitsPerSample == 8 &&
146 dsound->wfx.nChannels == dsb->wfx.nChannels) {
147 /* avoid needless 8->16->8 conversion */
148 *obuf=*ibuf;
149 if (dsb->wfx.nChannels==2)
150 *(obuf+1)=*(ibuf+1);
151 return;
153 fl = cvtU8toS16(*ibuf);
154 fr = (dsb->wfx.nChannels==2 ? cvtU8toS16(*(ibuf + 1)) : fl);
155 } else {
156 fl = *((INT16 *)ibuf);
157 fr = (dsb->wfx.nChannels==2 ? *(((INT16 *)ibuf) + 1) : fl);
160 if (dsound->wfx.nChannels == 2) {
161 if (dsound->wfx.wBitsPerSample == 8) {
162 *obuf = cvtS16toU8(fl);
163 *(obuf + 1) = cvtS16toU8(fr);
164 return;
166 if (dsound->wfx.wBitsPerSample == 16) {
167 *((INT16 *)obuf) = fl;
168 *(((INT16 *)obuf) + 1) = fr;
169 return;
172 if (dsound->wfx.nChannels == 1) {
173 fl = (fl + fr) >> 1;
174 if (dsound->wfx.wBitsPerSample == 8) {
175 *obuf = cvtS16toU8(fl);
176 return;
178 if (dsound->wfx.wBitsPerSample == 16) {
179 *((INT16 *)obuf) = fl;
180 return;
185 /* Now with PerfectPitch (tm) technology */
186 static INT DSOUND_MixerNorm(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
188 INT i, size, ipos, ilen;
189 BYTE *ibp, *obp;
190 INT iAdvance = dsb->wfx.nBlockAlign;
191 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
193 ibp = dsb->buffer + dsb->buf_mixpos;
194 obp = buf;
196 TRACE("(%p, %p, %p), buf_mixpos=%ld\n", dsb, ibp, obp, dsb->buf_mixpos);
197 /* Check for the best case */
198 if ((dsb->freq == dsb->dsound->wfx.nSamplesPerSec) &&
199 (dsb->wfx.wBitsPerSample == dsb->dsound->wfx.wBitsPerSample) &&
200 (dsb->wfx.nChannels == dsb->dsound->wfx.nChannels)) {
201 DWORD bytesleft = dsb->buflen - dsb->buf_mixpos;
202 TRACE("(%p) Best case\n", dsb);
203 if (len <= bytesleft )
204 memcpy(obp, ibp, len);
205 else { /* wrap */
206 memcpy(obp, ibp, bytesleft );
207 memcpy(obp + bytesleft, dsb->buffer, len - bytesleft);
209 return len;
212 /* Check for same sample rate */
213 if (dsb->freq == dsb->dsound->wfx.nSamplesPerSec) {
214 TRACE("(%p) Same sample rate %ld = primary %ld\n", dsb,
215 dsb->freq, dsb->dsound->wfx.nSamplesPerSec);
216 ilen = 0;
217 for (i = 0; i < len; i += oAdvance) {
218 cp_fields(dsb, ibp, obp );
219 ibp += iAdvance;
220 ilen += iAdvance;
221 obp += oAdvance;
222 if (ibp >= (BYTE *)(dsb->buffer + dsb->buflen))
223 ibp = dsb->buffer; /* wrap */
225 return (ilen);
228 /* Mix in different sample rates */
229 /* */
230 /* New PerfectPitch(tm) Technology (c) 1998 Rob Riggs */
231 /* Patent Pending :-] */
233 /* Patent enhancements (c) 2000 Ove KÃ¥ven,
234 * TransGaming Technologies Inc. */
236 /* FIXME("(%p) Adjusting frequency: %ld -> %ld (need optimization)\n",
237 dsb, dsb->freq, dsb->dsound->wfx.nSamplesPerSec); */
239 size = len / oAdvance;
240 ilen = 0;
241 ipos = dsb->buf_mixpos;
242 for (i = 0; i < size; i++) {
243 cp_fields(dsb, (dsb->buffer + ipos), obp);
244 obp += oAdvance;
245 dsb->freqAcc += dsb->freqAdjust;
246 if (dsb->freqAcc >= (1<<DSOUND_FREQSHIFT)) {
247 ULONG adv = (dsb->freqAcc>>DSOUND_FREQSHIFT) * iAdvance;
248 dsb->freqAcc &= (1<<DSOUND_FREQSHIFT)-1;
249 ipos += adv; ilen += adv;
250 while (ipos >= dsb->buflen)
251 ipos -= dsb->buflen;
254 return ilen;
257 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
259 INT i, inc = dsb->dsound->wfx.wBitsPerSample >> 3;
260 BYTE *bpc = buf;
261 INT16 *bps = (INT16 *) buf;
263 TRACE("(%p) left = %lx, right = %lx\n", dsb,
264 dsb->cvolpan.dwTotalLeftAmpFactor, dsb->cvolpan.dwTotalRightAmpFactor);
265 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->cvolpan.lPan == 0)) &&
266 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->cvolpan.lVolume == 0)) &&
267 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
268 return; /* Nothing to do */
270 /* If we end up with some bozo coder using panning or 3D sound */
271 /* with a mono primary buffer, it could sound very weird using */
272 /* this method. Oh well, tough patooties. */
274 for (i = 0; i < len; i += inc) {
275 INT val;
277 switch (inc) {
279 case 1:
280 /* 8-bit WAV is unsigned, but we need to operate */
281 /* on signed data for this to work properly */
282 val = *bpc - 128;
283 val = ((val * (i & inc ? dsb->cvolpan.dwTotalRightAmpFactor : dsb->cvolpan.dwTotalLeftAmpFactor)) >> 16);
284 *bpc = val + 128;
285 bpc++;
286 break;
287 case 2:
288 /* 16-bit WAV is signed -- much better */
289 val = *bps;
290 val = ((val * ((i & inc) ? dsb->cvolpan.dwTotalRightAmpFactor : dsb->cvolpan.dwTotalLeftAmpFactor)) >> 16);
291 *bps = val;
292 bps++;
293 break;
294 default:
295 /* Very ugly! */
296 FIXME("MixerVol had a nasty error\n");
301 static void *tmp_buffer;
302 static size_t tmp_buffer_len = 0;
304 static void *DSOUND_tmpbuffer(size_t len)
306 if (len>tmp_buffer_len) {
307 void *new_buffer = realloc(tmp_buffer, len);
308 if (new_buffer) {
309 tmp_buffer = new_buffer;
310 tmp_buffer_len = len;
312 return new_buffer;
314 return tmp_buffer;
317 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
319 INT i, len, ilen, temp, field;
320 INT advance = dsb->dsound->wfx.wBitsPerSample >> 3;
321 BYTE *buf, *ibuf, *obuf;
322 INT16 *ibufs, *obufs;
324 len = fraglen;
325 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
326 temp = MulDiv(dsb->dsound->wfx.nAvgBytesPerSec, dsb->buflen,
327 dsb->nAvgBytesPerSec) -
328 MulDiv(dsb->dsound->wfx.nAvgBytesPerSec, dsb->buf_mixpos,
329 dsb->nAvgBytesPerSec);
330 len = (len > temp) ? temp : len;
332 len &= ~3; /* 4 byte alignment */
334 if (len == 0) {
335 /* This should only happen if we aren't looping and temp < 4 */
337 /* We skip the remainder, so check for possible events */
338 DSOUND_CheckEvent(dsb, dsb->buflen - dsb->buf_mixpos);
339 /* Stop */
340 dsb->state = STATE_STOPPED;
341 dsb->playpos = 0;
342 dsb->last_playpos = 0;
343 dsb->buf_mixpos = 0;
344 dsb->leadin = FALSE;
345 /* Check for DSBPN_OFFSETSTOP */
346 DSOUND_CheckEvent(dsb, 0);
347 return 0;
350 /* Been seeing segfaults in malloc() for some reason... */
351 TRACE("allocating buffer (size = %d)\n", len);
352 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
353 return 0;
355 TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
357 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
358 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
359 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
360 DSOUND_MixerVol(dsb, ibuf, len);
362 obuf = dsb->dsound->buffer + writepos;
363 for (i = 0; i < len; i += advance) {
364 obufs = (INT16 *) obuf;
365 ibufs = (INT16 *) ibuf;
366 if (dsb->dsound->wfx.wBitsPerSample == 8) {
367 /* 8-bit WAV is unsigned */
368 field = (*ibuf - 128);
369 field += (*obuf - 128);
370 field = field > 127 ? 127 : field;
371 field = field < -128 ? -128 : field;
372 *obuf = field + 128;
373 } else {
374 /* 16-bit WAV is signed */
375 field = *ibufs;
376 field += *obufs;
377 field = field > 32767 ? 32767 : field;
378 field = field < -32768 ? -32768 : field;
379 *obufs = field;
381 ibuf += advance;
382 obuf += advance;
383 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
384 obuf = dsb->dsound->buffer;
386 /* free(buf); */
388 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY)
389 DSOUND_CheckEvent(dsb, ilen);
391 if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
392 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
393 * not the MIX position... but if the sound buffer is bigger than our prebuffering
394 * (which must be the case for the streaming buffers that need this hack anyway)
395 * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
396 dsb->leadin = FALSE;
399 dsb->buf_mixpos += ilen;
401 if (dsb->buf_mixpos >= dsb->buflen) {
402 if (!(dsb->playflags & DSBPLAY_LOOPING)) {
403 dsb->state = STATE_STOPPED;
404 dsb->playpos = 0;
405 dsb->last_playpos = 0;
406 dsb->buf_mixpos = 0;
407 dsb->leadin = FALSE;
408 DSOUND_CheckEvent(dsb, 0); /* For DSBPN_OFFSETSTOP */
409 } else {
410 /* wrap */
411 while (dsb->buf_mixpos >= dsb->buflen)
412 dsb->buf_mixpos -= dsb->buflen;
413 if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
414 dsb->leadin = FALSE; /* HACK: see above */
418 return len;
421 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
423 INT i, ilen, field;
424 INT advance = dsb->dsound->wfx.wBitsPerSample >> 3;
425 BYTE *buf, *ibuf, *obuf;
426 INT16 *ibufs, *obufs;
428 len &= ~3; /* 4 byte alignment */
430 TRACE("allocating buffer (size = %ld)\n", len);
431 if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
432 return;
434 TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
436 ilen = DSOUND_MixerNorm(dsb, ibuf, len);
437 if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
438 (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
439 DSOUND_MixerVol(dsb, ibuf, len);
441 /* subtract instead of add, to phase out premixed data */
442 obuf = dsb->dsound->buffer + writepos;
443 for (i = 0; i < len; i += advance) {
444 obufs = (INT16 *) obuf;
445 ibufs = (INT16 *) ibuf;
446 if (dsb->dsound->wfx.wBitsPerSample == 8) {
447 /* 8-bit WAV is unsigned */
448 field = (*ibuf - 128);
449 field -= (*obuf - 128);
450 field = field > 127 ? 127 : field;
451 field = field < -128 ? -128 : field;
452 *obuf = field + 128;
453 } else {
454 /* 16-bit WAV is signed */
455 field = *ibufs;
456 field -= *obufs;
457 field = field > 32767 ? 32767 : field;
458 field = field < -32768 ? -32768 : field;
459 *obufs = field;
461 ibuf += advance;
462 obuf += advance;
463 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
464 obuf = dsb->dsound->buffer;
466 /* free(buf); */
469 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
471 DWORD size, flen, len, npos, nlen;
472 INT iAdvance = dsb->wfx.nBlockAlign;
473 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
474 /* determine amount of premixed data to cancel */
475 DWORD primary_done =
476 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
477 dsb->primary_mixpos - writepos;
479 TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
481 /* backtrack the mix position */
482 size = primary_done / oAdvance;
483 flen = size * dsb->freqAdjust;
484 len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
485 flen &= (1<<DSOUND_FREQSHIFT)-1;
486 while (dsb->freqAcc < flen) {
487 len += iAdvance;
488 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
490 len %= dsb->buflen;
491 npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
492 dsb->buf_mixpos - len;
493 if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
494 /* stop backtracking at startpos */
495 npos = dsb->startpos;
496 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
497 dsb->buf_mixpos - npos;
498 flen = dsb->freqAcc;
499 nlen = len / dsb->wfx.nBlockAlign;
500 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
501 nlen *= dsb->dsound->wfx.nBlockAlign;
502 writepos =
503 ((dsb->primary_mixpos < nlen) ? dsb->dsound->buflen : 0) +
504 dsb->primary_mixpos - nlen;
507 dsb->freqAcc -= flen;
508 dsb->buf_mixpos = npos;
509 dsb->primary_mixpos = writepos;
511 TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
512 dsb->buf_mixpos, dsb->primary_mixpos, len);
514 if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
517 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
519 #if 0
520 DWORD i, size, flen, len, npos, nlen;
521 INT iAdvance = dsb->wfx.nBlockAlign;
522 INT oAdvance = dsb->dsound->wfx.nBlockAlign;
523 /* determine amount of premixed data to cancel */
524 DWORD buf_done =
525 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
526 dsb->buf_mixpos - buf_writepos;
527 #endif
529 WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
530 /* since this is not implemented yet, just cancel *ALL* prebuffering for now
531 * (which is faster anyway when there's only a single secondary buffer) */
532 dsb->dsound->need_remix = TRUE;
535 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
537 EnterCriticalSection(&dsb->lock);
538 if (dsb->state == STATE_PLAYING) {
539 #if 0 /* this may not be quite reliable yet */
540 dsb->need_remix = TRUE;
541 #else
542 dsb->dsound->need_remix = TRUE;
543 #endif
545 LeaveCriticalSection(&dsb->lock);
548 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
550 DWORD len, slen;
551 /* determine this buffer's write position */
552 DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, dsb->state & dsb->dsound->state, writepos,
553 writepos, dsb->primary_mixpos, dsb->buf_mixpos);
554 /* determine how much already-mixed data exists */
555 DWORD buf_done =
556 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
557 dsb->buf_mixpos - buf_writepos;
558 DWORD primary_done =
559 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
560 dsb->primary_mixpos - writepos;
561 DWORD adv_done =
562 ((dsb->dsound->mixpos < writepos) ? dsb->dsound->buflen : 0) +
563 dsb->dsound->mixpos - writepos;
564 int still_behind;
566 TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
567 TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
568 TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
569 mixlen);
570 TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
572 /* save write position for non-GETCURRENTPOSITION2... */
573 dsb->playpos = buf_writepos;
575 /* check whether CalcPlayPosition detected a mixing underrun */
576 if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
577 /* it did, but did we have more to play? */
578 if ((dsb->playflags & DSBPLAY_LOOPING) ||
579 (dsb->buf_mixpos < dsb->buflen)) {
580 /* yes, have to recover */
581 ERR("underrun on sound buffer %p\n", dsb);
582 TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
584 dsb->primary_mixpos = writepos;
585 primary_done = 0;
587 /* determine how far ahead we should mix */
588 if (((dsb->playflags & DSBPLAY_LOOPING) ||
589 (dsb->leadin && (dsb->probably_valid_to != 0))) &&
590 !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
591 /* if this is a streaming buffer, it typically means that
592 * we should defer mixing past probably_valid_to as long
593 * as we can, to avoid unnecessary remixing */
594 /* the heavy-looking calculations shouldn't be that bad,
595 * as any game isn't likely to be have more than 1 or 2
596 * streaming buffers in use at any time anyway... */
597 DWORD probably_valid_left =
598 (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
599 ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
600 dsb->probably_valid_to - buf_writepos;
601 /* check for leadin condition */
602 if ((probably_valid_left == 0) &&
603 (dsb->probably_valid_to == dsb->startpos) &&
604 dsb->leadin)
605 probably_valid_left = dsb->buflen;
606 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
607 dsb->probably_valid_to, probably_valid_left);
608 /* check whether the app's time is already up */
609 if (probably_valid_left < dsb->writelead) {
610 WARN("probably_valid_to now within writelead, possible streaming underrun\n");
611 /* once we pass the point of no return,
612 * no reason to hold back anymore */
613 dsb->probably_valid_to = (DWORD)-1;
614 /* we just have to go ahead and mix what we have,
615 * there's no telling what the app is thinking anyway */
616 } else {
617 /* adjust for our frequency and our sample size */
618 probably_valid_left = MulDiv(probably_valid_left,
619 1 << DSOUND_FREQSHIFT,
620 dsb->wfx.nBlockAlign * dsb->freqAdjust) *
621 dsb->dsound->wfx.nBlockAlign;
622 /* check whether to clip mix_len */
623 if (probably_valid_left < mixlen) {
624 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
625 mixlen = probably_valid_left;
629 /* cut mixlen with what's already been mixed */
630 if (mixlen < primary_done) {
631 /* huh? and still CalcPlayPosition didn't
632 * detect an underrun? */
633 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
634 return 0;
636 len = mixlen - primary_done;
637 TRACE("remaining mixlen=%ld\n", len);
639 if (len < dsb->dsound->fraglen) {
640 /* smaller than a fragment, wait until it gets larger
641 * before we take the mixing overhead */
642 TRACE("mixlen not worth it, deferring mixing\n");
643 return 0;
646 /* ok, we know how much to mix, let's go */
647 still_behind = (adv_done > primary_done);
648 while (len) {
649 slen = dsb->dsound->buflen - dsb->primary_mixpos;
650 if (slen > len) slen = len;
651 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
653 if ((dsb->primary_mixpos < dsb->dsound->mixpos) &&
654 (dsb->primary_mixpos + slen >= dsb->dsound->mixpos))
655 still_behind = FALSE;
657 dsb->primary_mixpos += slen; len -= slen;
658 while (dsb->primary_mixpos >= dsb->dsound->buflen)
659 dsb->primary_mixpos -= dsb->dsound->buflen;
661 if ((dsb->state == STATE_STOPPED) || !slen) break;
663 TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->mixpos);
664 TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
665 /* return how far we think the primary buffer can
666 * advance its underrun detector...*/
667 if (still_behind) return 0;
668 if ((mixlen - len) < primary_done) return 0;
669 slen = ((dsb->primary_mixpos < dsb->dsound->mixpos) ?
670 dsb->dsound->buflen : 0) + dsb->primary_mixpos -
671 dsb->dsound->mixpos;
672 if (slen > mixlen) {
673 /* the primary_done and still_behind checks above should have worked */
674 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
675 slen = 0;
677 return slen;
680 static DWORD DSOUND_MixToPrimary(DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
682 INT i, len, maxlen = 0;
683 IDirectSoundBufferImpl *dsb;
685 TRACE("(%ld,%ld,%ld)\n", playpos, writepos, mixlen);
686 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
687 dsb = dsound->buffers[i];
689 if (!dsb || !(ICOM_VTBL(dsb)))
690 continue;
691 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
692 TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
693 EnterCriticalSection(&(dsb->lock));
694 if (dsb->state == STATE_STOPPING) {
695 DSOUND_MixCancel(dsb, writepos, TRUE);
696 dsb->state = STATE_STOPPED;
697 } else {
698 if ((dsb->state == STATE_STARTING) || recover) {
699 dsb->primary_mixpos = writepos;
700 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
701 dsb->need_remix = FALSE;
703 else if (dsb->need_remix) {
704 DSOUND_MixCancel(dsb, writepos, TRUE);
705 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
706 dsb->need_remix = FALSE;
708 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
709 if (dsb->state == STATE_STARTING)
710 dsb->state = STATE_PLAYING;
711 maxlen = (len > maxlen) ? len : maxlen;
713 LeaveCriticalSection(&(dsb->lock));
717 return maxlen;
720 static void DSOUND_MixReset(DWORD writepos)
722 INT i;
723 IDirectSoundBufferImpl *dsb;
724 int nfiller;
726 TRACE("(%ld)\n", writepos);
728 /* the sound of silence */
729 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
731 /* reset all buffer mix positions */
732 for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
733 dsb = dsound->buffers[i];
735 if (!dsb || !(ICOM_VTBL(dsb)))
736 continue;
737 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
738 TRACE("Resetting %p\n", dsb);
739 EnterCriticalSection(&(dsb->lock));
740 if (dsb->state == STATE_STOPPING) {
741 dsb->state = STATE_STOPPED;
743 else if (dsb->state == STATE_STARTING) {
744 /* nothing */
745 } else {
746 DSOUND_MixCancel(dsb, writepos, FALSE);
747 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
748 dsb->need_remix = FALSE;
750 LeaveCriticalSection(&(dsb->lock));
754 /* wipe out premixed data */
755 if (dsound->mixpos < writepos) {
756 memset(dsound->buffer + writepos, nfiller, dsound->buflen - writepos);
757 memset(dsound->buffer, nfiller, dsound->mixpos);
758 } else {
759 memset(dsound->buffer + writepos, nfiller, dsound->mixpos - writepos);
762 /* reset primary mix position */
763 dsound->mixpos = writepos;
766 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
768 if (dsound->need_remix) {
769 DSOUND_MixReset(writepos);
770 dsound->need_remix = FALSE;
771 /* maximize Half-Life performance */
772 dsound->prebuf = ds_snd_queue_min;
773 dsound->precount = 0;
774 } else {
775 dsound->precount++;
776 if (dsound->precount >= 4) {
777 if (dsound->prebuf < ds_snd_queue_max)
778 dsound->prebuf++;
779 dsound->precount = 0;
782 TRACE("premix adjust: %d\n", dsound->prebuf);
785 void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
787 if (mixq + dsound->pwqueue > ds_hel_queue) mixq = ds_hel_queue - dsound->pwqueue;
788 TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
789 for (; mixq; mixq--) {
790 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
791 dsound->pwwrite++;
792 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
793 dsound->pwqueue++;
797 /* #define SYNC_CALLBACK */
799 void DSOUND_PerformMix(void)
801 int nfiller;
802 BOOL forced;
803 HRESULT hres;
805 RtlAcquireResourceShared(&(dsound->lock), TRUE);
807 if (!dsound || !dsound->ref) {
808 /* seems the dsound object is currently being released */
809 RtlReleaseResource(&(dsound->lock));
810 return;
813 /* the sound of silence */
814 nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
816 /* whether the primary is forced to play even without secondary buffers */
817 forced = ((dsound->state == STATE_PLAYING) || (dsound->state == STATE_STARTING));
819 TRACE("entering at %ld\n", GetTickCount());
820 if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
821 BOOL paused = ((dsound->state == STATE_STOPPED) || (dsound->state == STATE_STARTING));
822 /* FIXME: document variables */
823 DWORD playpos, writepos, inq, maxq, frag;
824 if (dsound->hwbuf) {
825 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, &writepos);
826 if (hres) {
827 RtlReleaseResource(&(dsound->lock));
828 return;
830 /* Well, we *could* do Just-In-Time mixing using the writepos,
831 * but that's a little bit ambitious and unnecessary... */
832 /* rather add our safety margin to the writepos, if we're playing */
833 if (!paused) {
834 writepos += dsound->writelead;
835 while (writepos >= dsound->buflen)
836 writepos -= dsound->buflen;
837 } else writepos = playpos;
839 else {
840 playpos = dsound->pwplay * dsound->fraglen;
841 writepos = playpos;
842 if (!paused) {
843 writepos += ds_hel_margin * dsound->fraglen;
844 while (writepos >= dsound->buflen)
845 writepos -= dsound->buflen;
848 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld\n",
849 playpos,writepos,dsound->playpos,dsound->mixpos);
850 /* wipe out just-played sound data */
851 if (playpos < dsound->playpos) {
852 memset(dsound->buffer + dsound->playpos, nfiller, dsound->buflen - dsound->playpos);
853 memset(dsound->buffer, nfiller, playpos);
854 } else {
855 memset(dsound->buffer + dsound->playpos, nfiller, playpos - dsound->playpos);
857 dsound->playpos = playpos;
859 EnterCriticalSection(&(dsound->mixlock));
861 /* reset mixing if necessary */
862 DSOUND_CheckReset(dsound, writepos);
864 /* check how much prebuffering is left */
865 inq = dsound->mixpos;
866 if (inq < writepos)
867 inq += dsound->buflen;
868 inq -= writepos;
870 /* find the maximum we can prebuffer */
871 if (!paused) {
872 maxq = playpos;
873 if (maxq < writepos)
874 maxq += dsound->buflen;
875 maxq -= writepos;
876 } else maxq = dsound->buflen;
878 /* clip maxq to dsound->prebuf */
879 frag = dsound->prebuf * dsound->fraglen;
880 if (maxq > frag) maxq = frag;
882 /* check for consistency */
883 if (inq > maxq) {
884 /* the playback position must have passed our last
885 * mixed position, i.e. it's an underrun, or we have
886 * nothing more to play */
887 TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
888 inq = 0;
889 /* stop the playback now, to allow buffers to refill */
890 if (dsound->state == STATE_PLAYING) {
891 dsound->state = STATE_STARTING;
893 else if (dsound->state == STATE_STOPPING) {
894 dsound->state = STATE_STOPPED;
896 else {
897 /* how can we have an underrun if we aren't playing? */
898 WARN("unexpected primary state (%ld)\n", dsound->state);
900 #ifdef SYNC_CALLBACK
901 /* DSOUND_callback may need this lock */
902 LeaveCriticalSection(&(dsound->mixlock));
903 #endif
904 DSOUND_PrimaryStop(dsound);
905 #ifdef SYNC_CALLBACK
906 EnterCriticalSection(&(dsound->mixlock));
907 #endif
908 if (dsound->hwbuf) {
909 /* the Stop is supposed to reset play position to beginning of buffer */
910 /* unfortunately, OSS is not able to do so, so get current pointer */
911 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, NULL);
912 if (hres) {
913 LeaveCriticalSection(&(dsound->mixlock));
914 RtlReleaseResource(&(dsound->lock));
915 return;
917 } else {
918 playpos = dsound->pwplay * dsound->fraglen;
920 writepos = playpos;
921 dsound->playpos = playpos;
922 dsound->mixpos = writepos;
923 inq = 0;
924 maxq = dsound->buflen;
925 if (maxq > frag) maxq = frag;
926 memset(dsound->buffer, nfiller, dsound->buflen);
927 paused = TRUE;
930 /* do the mixing */
931 frag = DSOUND_MixToPrimary(playpos, writepos, maxq, paused);
932 if (forced) frag = maxq - inq;
933 dsound->mixpos += frag;
934 while (dsound->mixpos >= dsound->buflen)
935 dsound->mixpos -= dsound->buflen;
937 if (frag) {
938 /* buffers have been filled, restart playback */
939 if (dsound->state == STATE_STARTING) {
940 dsound->state = STATE_PLAYING;
942 else if (dsound->state == STATE_STOPPED) {
943 /* the dsound is supposed to play if there's something to play
944 * even if it is reported as stopped, so don't let this confuse you */
945 dsound->state = STATE_STOPPING;
947 LeaveCriticalSection(&(dsound->mixlock));
948 if (paused) {
949 DSOUND_PrimaryPlay(dsound);
950 TRACE("starting playback\n");
953 else
954 LeaveCriticalSection(&(dsound->mixlock));
955 } else {
956 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
957 if (dsound->state == STATE_STARTING) {
958 DSOUND_PrimaryPlay(dsound);
959 dsound->state = STATE_PLAYING;
961 else if (dsound->state == STATE_STOPPING) {
962 DSOUND_PrimaryStop(dsound);
963 dsound->state = STATE_STOPPED;
966 TRACE("completed processing at %ld\n", GetTickCount());
967 RtlReleaseResource(&(dsound->lock));
970 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
972 if (!dsound) {
973 ERR("dsound died without killing us?\n");
974 timeKillEvent(timerID);
975 timeEndPeriod(DS_TIME_RES);
976 return;
979 TRACE("entered\n");
980 DSOUND_PerformMix();
983 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
985 IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
986 TRACE("entering at %ld, msg=%08x\n", GetTickCount(), msg);
987 if (msg == MM_WOM_DONE) {
988 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
989 if (This->pwqueue == (DWORD)-1) {
990 TRACE("completed due to reset\n");
991 return;
993 /* it could be a bad idea to enter critical section here... if there's lock contention,
994 * the resulting scheduling delays might obstruct the winmm player thread */
995 #ifdef SYNC_CALLBACK
996 EnterCriticalSection(&(This->mixlock));
997 #endif
998 /* retrieve current values */
999 fraglen = dsound->fraglen;
1000 buflen = dsound->buflen;
1001 pwplay = dsound->pwplay;
1002 playpos = pwplay * fraglen;
1003 mixpos = dsound->mixpos;
1004 /* check remaining mixed data */
1005 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1006 mixq = inq / fraglen;
1007 if ((inq - (mixq * fraglen)) > 0) mixq++;
1008 /* complete the playing buffer */
1009 TRACE("done playing primary pos=%ld\n", playpos);
1010 pwplay++;
1011 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1012 /* write new values */
1013 dsound->pwplay = pwplay;
1014 dsound->pwqueue--;
1015 /* queue new buffer if we have data for it */
1016 if (inq>1) DSOUND_WaveQueue(This, inq-1);
1017 #ifdef SYNC_CALLBACK
1018 LeaveCriticalSection(&(This->mixlock));
1019 #endif
1021 TRACE("completed\n");