Avoid local WINAPI function pointers in _invoke.
[wine] / dlls / dsound / mixer.c
1 /*                      DirectSound
2  *
3  * Copyright 1998 Marcus Meissner
4  * Copyright 1998 Rob Riggs
5  * Copyright 2000-2002 TransGaming Technologies, Inc.
6  *
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.
11  *
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.
16  *
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
20  */
21
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 */
33
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"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
49
50 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
51 {
52         double temp;
53
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 */
57
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);
63
64         TRACE("left = %lx, right = %lx\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
65 }
66
67 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
68 {
69         DWORD sw;
70
71         sw = dsb->wfx.nChannels * (dsb->wfx.wBitsPerSample / 8);
72         /* calculate the 10ms write lead */
73         dsb->writelead = (dsb->freq / 100) * sw;
74 }
75
76 void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len)
77 {
78         int                     i;
79         DWORD                   offset;
80         LPDSBPOSITIONNOTIFY     event;
81
82         if (dsb->nrofnotifies == 0)
83                 return;
84
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;
104                 }
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);
110                         }
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);
115                         }
116                 }
117         }
118 }
119
120 /* WAV format info can be found at:
121  *
122  *    http://www.cwi.nl/ftp/audio/AudioFormats.part2
123  *    ftp://ftp.cwi.nl/pub/audio/RIFF-format
124  *
125  * Import points to remember:
126  *    8-bit WAV is unsigned
127  *    16-bit WAV is signed
128  */
129  /* Use the same formulas as pcmconverter.c */
130 static inline INT16 cvtU8toS16(BYTE b)
131 {
132     return (short)((b+(b << 8))-32768);
133 }
134
135 static inline BYTE cvtS16toU8(INT16 s)
136 {
137     return (s >> 8) ^ (unsigned char)0x80;
138 }
139
140 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, BYTE *ibuf, BYTE *obuf )
141 {
142         INT fl,fr;
143
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;
152                 }
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);
158         }
159
160         if (dsound->wfx.nChannels == 2) {
161                 if (dsound->wfx.wBitsPerSample == 8) {
162                         *obuf = cvtS16toU8(fl);
163                         *(obuf + 1) = cvtS16toU8(fr);
164                         return;
165                 }
166                 if (dsound->wfx.wBitsPerSample == 16) {
167                         *((INT16 *)obuf) = fl;
168                         *(((INT16 *)obuf) + 1) = fr;
169                         return;
170                 }
171         }
172         if (dsound->wfx.nChannels == 1) {
173                 fl = (fl + fr) >> 1;
174                 if (dsound->wfx.wBitsPerSample == 8) {
175                         *obuf = cvtS16toU8(fl);
176                         return;
177                 }
178                 if (dsound->wfx.wBitsPerSample == 16) {
179                         *((INT16 *)obuf) = fl;
180                         return;
181                 }
182         }
183 }
184
185 /* Now with PerfectPitch (tm) technology */
186 static INT DSOUND_MixerNorm(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
187 {
188         INT     i, size, ipos, ilen;
189         BYTE    *ibp, *obp;
190         INT     iAdvance = dsb->wfx.nBlockAlign;
191         INT     oAdvance = dsb->dsound->wfx.nBlockAlign;
192
193         ibp = dsb->buffer + dsb->buf_mixpos;
194         obp = buf;
195
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);
208                 }
209                 return len;
210         }
211
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 */
224                 }
225                 return (ilen);
226         }
227
228         /* Mix in different sample rates */
229         /* */
230         /* New PerfectPitch(tm) Technology (c) 1998 Rob Riggs */
231         /* Patent Pending :-] */
232
233         /* Patent enhancements (c) 2000 Ove Kåven,
234          * TransGaming Technologies Inc. */
235
236         /* FIXME("(%p) Adjusting frequency: %ld -> %ld (need optimization)\n",
237            dsb, dsb->freq, dsb->dsound->wfx.nSamplesPerSec); */
238
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;
252                 }
253         }
254         return ilen;
255 }
256
257 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
258 {
259         INT     i, inc = dsb->dsound->wfx.wBitsPerSample >> 3;
260         BYTE    *bpc = buf;
261         INT16   *bps = (INT16 *) buf;
262
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 */
269
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. */
273
274         for (i = 0; i < len; i += inc) {
275                 INT     val;
276
277                 switch (inc) {
278
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");
297                 }
298         }
299 }
300
301 static void *tmp_buffer;
302 static size_t tmp_buffer_len = 0;
303
304 static void *DSOUND_tmpbuffer(size_t len)
305 {
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;
311     }
312     return new_buffer;
313   }
314   return tmp_buffer;
315 }
316
317 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
318 {
319         INT     i, len, ilen, temp, field, nBlockAlign;
320         INT     advance = dsb->dsound->wfx.wBitsPerSample >> 3;
321         BYTE    *buf, *ibuf, *obuf;
322         INT16   *ibufs, *obufs;
323
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;
331         }
332         nBlockAlign = dsb->dsound->wfx.nBlockAlign;
333         len = len / nBlockAlign * nBlockAlign;  /* data alignment */
334
335         if (len == 0) {
336                 /* This should only happen if we aren't looping and temp < nBlockAlign */
337                 return 0;
338         }
339
340         /* Been seeing segfaults in malloc() for some reason... */
341         TRACE("allocating buffer (size = %d)\n", len);
342         if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
343                 return 0;
344
345         TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
346
347         ilen = DSOUND_MixerNorm(dsb, ibuf, len);
348         if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
349             (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
350                 DSOUND_MixerVol(dsb, ibuf, len);
351
352         obuf = dsb->dsound->buffer + writepos;
353         for (i = 0; i < len; i += advance) {
354                 obufs = (INT16 *) obuf;
355                 ibufs = (INT16 *) ibuf;
356                 if (dsb->dsound->wfx.wBitsPerSample == 8) {
357                         /* 8-bit WAV is unsigned */
358                         field = (*ibuf - 128);
359                         field += (*obuf - 128);
360                         field = field > 127 ? 127 : field;
361                         field = field < -128 ? -128 : field;
362                         *obuf = field + 128;
363                 } else {
364                         /* 16-bit WAV is signed */
365                         field = *ibufs;
366                         field += *obufs;
367                         field = field > 32767 ? 32767 : field;
368                         field = field < -32768 ? -32768 : field;
369                         *obufs = field;
370                 }
371                 ibuf += advance;
372                 obuf += advance;
373                 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
374                         obuf = dsb->dsound->buffer;
375         }
376         /* free(buf); */
377
378         if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
379                 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
380                  * not the MIX position... but if the sound buffer is bigger than our prebuffering
381                  * (which must be the case for the streaming buffers that need this hack anyway)
382                  * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
383                 dsb->leadin = FALSE;
384         }
385
386         dsb->buf_mixpos += ilen;
387
388         if (dsb->buf_mixpos >= dsb->buflen) {
389                 if (dsb->playflags & DSBPLAY_LOOPING) {
390                         /* wrap */
391                         while (dsb->buf_mixpos >= dsb->buflen)
392                                 dsb->buf_mixpos -= dsb->buflen;
393                         if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
394                                 dsb->leadin = FALSE; /* HACK: see above */
395                 }
396         }
397
398         return len;
399 }
400
401 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
402 {
403         INT     i, ilen, field, nBlockAlign;
404         INT     advance = dsb->dsound->wfx.wBitsPerSample >> 3;
405         BYTE    *buf, *ibuf, *obuf;
406         INT16   *ibufs, *obufs;
407
408         nBlockAlign = dsb->dsound->wfx.nBlockAlign;
409         len = len / nBlockAlign * nBlockAlign;  /* data alignment */
410
411         TRACE("allocating buffer (size = %ld)\n", len);
412         if ((buf = ibuf = (BYTE *) DSOUND_tmpbuffer(len)) == NULL)
413                 return;
414
415         TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
416
417         ilen = DSOUND_MixerNorm(dsb, ibuf, len);
418         if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
419             (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME))
420                 DSOUND_MixerVol(dsb, ibuf, len);
421
422         /* subtract instead of add, to phase out premixed data */
423         obuf = dsb->dsound->buffer + writepos;
424         for (i = 0; i < len; i += advance) {
425                 obufs = (INT16 *) obuf;
426                 ibufs = (INT16 *) ibuf;
427                 if (dsb->dsound->wfx.wBitsPerSample == 8) {
428                         /* 8-bit WAV is unsigned */
429                         field = (*ibuf - 128);
430                         field -= (*obuf - 128);
431                         field = field > 127 ? 127 : field;
432                         field = field < -128 ? -128 : field;
433                         *obuf = field + 128;
434                 } else {
435                         /* 16-bit WAV is signed */
436                         field = *ibufs;
437                         field -= *obufs;
438                         field = field > 32767 ? 32767 : field;
439                         field = field < -32768 ? -32768 : field;
440                         *obufs = field;
441                 }
442                 ibuf += advance;
443                 obuf += advance;
444                 if (obuf >= (BYTE *)(dsb->dsound->buffer + dsb->dsound->buflen))
445                         obuf = dsb->dsound->buffer;
446         }
447         /* free(buf); */
448 }
449
450 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
451 {
452         DWORD   size, flen, len, npos, nlen;
453         INT     iAdvance = dsb->wfx.nBlockAlign;
454         INT     oAdvance = dsb->dsound->wfx.nBlockAlign;
455         /* determine amount of premixed data to cancel */
456         DWORD primary_done =
457                 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
458                 dsb->primary_mixpos - writepos;
459
460         TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
461
462         /* backtrack the mix position */
463         size = primary_done / oAdvance;
464         flen = size * dsb->freqAdjust;
465         len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
466         flen &= (1<<DSOUND_FREQSHIFT)-1;
467         while (dsb->freqAcc < flen) {
468                 len += iAdvance;
469                 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
470         }
471         len %= dsb->buflen;
472         npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
473                 dsb->buf_mixpos - len;
474         if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
475                 /* stop backtracking at startpos */
476                 npos = dsb->startpos;
477                 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
478                         dsb->buf_mixpos - npos;
479                 flen = dsb->freqAcc;
480                 nlen = len / dsb->wfx.nBlockAlign;
481                 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
482                 nlen *= dsb->dsound->wfx.nBlockAlign;
483                 writepos =
484                         ((dsb->primary_mixpos < nlen) ? dsb->dsound->buflen : 0) +
485                         dsb->primary_mixpos - nlen;
486         }
487
488         dsb->freqAcc -= flen;
489         dsb->buf_mixpos = npos;
490         dsb->primary_mixpos = writepos;
491
492         TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
493               dsb->buf_mixpos, dsb->primary_mixpos, len);
494
495         if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
496 }
497
498 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
499 {
500 #if 0
501         DWORD   i, size, flen, len, npos, nlen;
502         INT     iAdvance = dsb->wfx.nBlockAlign;
503         INT     oAdvance = dsb->dsound->wfx.nBlockAlign;
504         /* determine amount of premixed data to cancel */
505         DWORD buf_done =
506                 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
507                 dsb->buf_mixpos - buf_writepos;
508 #endif
509
510         WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
511         /* since this is not implemented yet, just cancel *ALL* prebuffering for now
512          * (which is faster anyway when there's only a single secondary buffer) */
513         dsb->dsound->need_remix = TRUE;
514 }
515
516 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
517 {
518         EnterCriticalSection(&dsb->lock);
519         if (dsb->state == STATE_PLAYING) {
520 #if 0 /* this may not be quite reliable yet */
521                 dsb->need_remix = TRUE;
522 #else
523                 dsb->dsound->need_remix = TRUE;
524 #endif
525         }
526         LeaveCriticalSection(&dsb->lock);
527 }
528
529 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
530 {
531         DWORD len, slen;
532         /* determine this buffer's write position */
533         DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, dsb->state & dsb->dsound->state, writepos,
534                                                      writepos, dsb->primary_mixpos, dsb->buf_mixpos);
535         /* determine how much already-mixed data exists */
536         DWORD buf_done =
537                 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
538                 dsb->buf_mixpos - buf_writepos;
539         DWORD primary_done =
540                 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
541                 dsb->primary_mixpos - writepos;
542         DWORD adv_done =
543                 ((dsb->dsound->mixpos < writepos) ? dsb->dsound->buflen : 0) +
544                 dsb->dsound->mixpos - writepos;
545         DWORD played =
546                 ((buf_writepos < dsb->playpos) ? dsb->buflen : 0) +
547                 buf_writepos - dsb->playpos;
548         DWORD buf_left = dsb->buflen - buf_writepos;
549         int still_behind;
550
551         TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
552         TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
553         TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
554               mixlen);
555         TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
556
557         /* check for notification positions */
558         if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
559             dsb->state != STATE_STARTING) {
560                 DSOUND_CheckEvent(dsb, played);
561         }
562
563         /* save write position for non-GETCURRENTPOSITION2... */
564         dsb->playpos = buf_writepos;
565
566         /* check whether CalcPlayPosition detected a mixing underrun */
567         if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
568                 /* it did, but did we have more to play? */
569                 if ((dsb->playflags & DSBPLAY_LOOPING) ||
570                     (dsb->buf_mixpos < dsb->buflen)) {
571                         /* yes, have to recover */
572                         ERR("underrun on sound buffer %p\n", dsb);
573                         TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
574                 }
575                 dsb->primary_mixpos = writepos;
576                 primary_done = 0;
577         }
578         /* determine how far ahead we should mix */
579         if (((dsb->playflags & DSBPLAY_LOOPING) ||
580              (dsb->leadin && (dsb->probably_valid_to != 0))) &&
581             !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
582                 /* if this is a streaming buffer, it typically means that
583                  * we should defer mixing past probably_valid_to as long
584                  * as we can, to avoid unnecessary remixing */
585                 /* the heavy-looking calculations shouldn't be that bad,
586                  * as any game isn't likely to be have more than 1 or 2
587                  * streaming buffers in use at any time anyway... */
588                 DWORD probably_valid_left =
589                         (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
590                         ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
591                         dsb->probably_valid_to - buf_writepos;
592                 /* check for leadin condition */
593                 if ((probably_valid_left == 0) &&
594                     (dsb->probably_valid_to == dsb->startpos) &&
595                     dsb->leadin)
596                         probably_valid_left = dsb->buflen;
597                 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
598                       dsb->probably_valid_to, probably_valid_left);
599                 /* check whether the app's time is already up */
600                 if (probably_valid_left < dsb->writelead) {
601                         WARN("probably_valid_to now within writelead, possible streaming underrun\n");
602                         /* once we pass the point of no return,
603                          * no reason to hold back anymore */
604                         dsb->probably_valid_to = (DWORD)-1;
605                         /* we just have to go ahead and mix what we have,
606                          * there's no telling what the app is thinking anyway */
607                 } else {
608                         /* adjust for our frequency and our sample size */
609                         probably_valid_left = MulDiv(probably_valid_left,
610                                                      1 << DSOUND_FREQSHIFT,
611                                                      dsb->wfx.nBlockAlign * dsb->freqAdjust) *
612                                               dsb->dsound->wfx.nBlockAlign;
613                         /* check whether to clip mix_len */
614                         if (probably_valid_left < mixlen) {
615                                 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
616                                 mixlen = probably_valid_left;
617                         }
618                 }
619         }
620         /* cut mixlen with what's already been mixed */
621         if (mixlen < primary_done) {
622                 /* huh? and still CalcPlayPosition didn't
623                  * detect an underrun? */
624                 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
625                 return 0;
626         }
627         len = mixlen - primary_done;
628         TRACE("remaining mixlen=%ld\n", len);
629
630         if (len < dsb->dsound->fraglen) {
631                 /* smaller than a fragment, wait until it gets larger
632                  * before we take the mixing overhead */
633                 TRACE("mixlen not worth it, deferring mixing\n");
634                 still_behind = 1;
635                 goto post_mix;
636         }
637
638         /* ok, we know how much to mix, let's go */
639         still_behind = (adv_done > primary_done);
640         while (len) {
641                 slen = dsb->dsound->buflen - dsb->primary_mixpos;
642                 if (slen > len) slen = len;
643                 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
644
645                 if ((dsb->primary_mixpos < dsb->dsound->mixpos) &&
646                     (dsb->primary_mixpos + slen >= dsb->dsound->mixpos))
647                         still_behind = FALSE;
648
649                 dsb->primary_mixpos += slen; len -= slen;
650                 while (dsb->primary_mixpos >= dsb->dsound->buflen)
651                         dsb->primary_mixpos -= dsb->dsound->buflen;
652
653                 if ((dsb->state == STATE_STOPPED) || !slen) break;
654         }
655         TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->mixpos);
656         TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
657
658 post_mix:
659         /* check if buffer should be considered complete */
660         if (buf_left < dsb->writelead &&
661             !(dsb->playflags & DSBPLAY_LOOPING)) {
662                 dsb->state = STATE_STOPPED;
663                 dsb->playpos = 0;
664                 dsb->last_playpos = 0;
665                 dsb->buf_mixpos = 0;
666                 dsb->leadin = FALSE;
667                 DSOUND_CheckEvent(dsb, buf_left);
668         }
669
670         /* return how far we think the primary buffer can
671          * advance its underrun detector...*/
672         if (still_behind) return 0;
673         if ((mixlen - len) < primary_done) return 0;
674         slen = ((dsb->primary_mixpos < dsb->dsound->mixpos) ?
675                 dsb->dsound->buflen : 0) + dsb->primary_mixpos -
676                 dsb->dsound->mixpos;
677         if (slen > mixlen) {
678                 /* the primary_done and still_behind checks above should have worked */
679                 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
680                 slen = 0;
681         }
682         return slen;
683 }
684
685 static DWORD DSOUND_MixToPrimary(DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
686 {
687         INT                     i, len, maxlen = 0;
688         IDirectSoundBufferImpl  *dsb;
689
690         TRACE("(%ld,%ld,%ld)\n", playpos, writepos, mixlen);
691         for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
692                 dsb = dsound->buffers[i];
693
694                 if (!dsb || !dsb->lpVtbl)
695                         continue;
696                 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
697                         TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
698                         EnterCriticalSection(&(dsb->lock));
699                         if (dsb->state == STATE_STOPPING) {
700                                 DSOUND_MixCancel(dsb, writepos, TRUE);
701                                 dsb->state = STATE_STOPPED;
702                                 DSOUND_CheckEvent(dsb, 0);
703                         } else {
704                                 if ((dsb->state == STATE_STARTING) || recover) {
705                                         dsb->primary_mixpos = writepos;
706                                         memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
707                                         dsb->need_remix = FALSE;
708                                 }
709                                 else if (dsb->need_remix) {
710                                         DSOUND_MixCancel(dsb, writepos, TRUE);
711                                         memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
712                                         dsb->need_remix = FALSE;
713                                 }
714                                 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
715                                 if (dsb->state == STATE_STARTING)
716                                         dsb->state = STATE_PLAYING;
717                                 maxlen = (len > maxlen) ? len : maxlen;
718                         }
719                         LeaveCriticalSection(&(dsb->lock));
720                 }
721         }
722
723         return maxlen;
724 }
725
726 static void DSOUND_MixReset(DWORD writepos)
727 {
728         INT                     i;
729         IDirectSoundBufferImpl  *dsb;
730         int nfiller;
731
732         TRACE("(%ld)\n", writepos);
733
734         /* the sound of silence */
735         nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
736
737         /* reset all buffer mix positions */
738         for (i = dsound->nrofbuffers - 1; i >= 0; i--) {
739                 dsb = dsound->buffers[i];
740
741                 if (!dsb || !dsb->lpVtbl)
742                         continue;
743                 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
744                         TRACE("Resetting %p\n", dsb);
745                         EnterCriticalSection(&(dsb->lock));
746                         if (dsb->state == STATE_STOPPING) {
747                                 dsb->state = STATE_STOPPED;
748                         }
749                         else if (dsb->state == STATE_STARTING) {
750                                 /* nothing */
751                         } else {
752                                 DSOUND_MixCancel(dsb, writepos, FALSE);
753                                 memcpy(&dsb->cvolpan, &dsb->volpan, sizeof(dsb->cvolpan));
754                                 dsb->need_remix = FALSE;
755                         }
756                         LeaveCriticalSection(&(dsb->lock));
757                 }
758         }
759
760         /* wipe out premixed data */
761         if (dsound->mixpos < writepos) {
762                 memset(dsound->buffer + writepos, nfiller, dsound->buflen - writepos);
763                 memset(dsound->buffer, nfiller, dsound->mixpos);
764         } else {
765                 memset(dsound->buffer + writepos, nfiller, dsound->mixpos - writepos);
766         }
767
768         /* reset primary mix position */
769         dsound->mixpos = writepos;
770 }
771
772 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
773 {
774         if (dsound->need_remix) {
775                 DSOUND_MixReset(writepos);
776                 dsound->need_remix = FALSE;
777                 /* maximize Half-Life performance */
778                 dsound->prebuf = ds_snd_queue_min;
779                 dsound->precount = 0;
780         } else {
781                 dsound->precount++;
782                 if (dsound->precount >= 4) {
783                         if (dsound->prebuf < ds_snd_queue_max)
784                                 dsound->prebuf++;
785                         dsound->precount = 0;
786                 }
787         }
788         TRACE("premix adjust: %d\n", dsound->prebuf);
789 }
790
791 void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
792 {
793         if (mixq + dsound->pwqueue > ds_hel_queue) mixq = ds_hel_queue - dsound->pwqueue;
794         TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
795         for (; mixq; mixq--) {
796                 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
797                 dsound->pwwrite++;
798                 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
799                 dsound->pwqueue++;
800         }
801 }
802
803 /* #define SYNC_CALLBACK */
804
805 void DSOUND_PerformMix(void)
806 {
807         int nfiller;
808         BOOL forced;
809         HRESULT hres;
810
811         RtlAcquireResourceShared(&(dsound->lock), TRUE);
812
813         if (!dsound || !dsound->ref) {
814                 /* seems the dsound object is currently being released */
815                 RtlReleaseResource(&(dsound->lock));
816                 return;
817         }
818
819         /* the sound of silence */
820         nfiller = dsound->wfx.wBitsPerSample == 8 ? 128 : 0;
821
822         /* whether the primary is forced to play even without secondary buffers */
823         forced = ((dsound->state == STATE_PLAYING) || (dsound->state == STATE_STARTING));
824
825         TRACE("entering at %ld\n", GetTickCount());
826         if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
827                 BOOL paused = ((dsound->state == STATE_STOPPED) || (dsound->state == STATE_STARTING));
828                 /* FIXME: document variables */
829                 DWORD playpos, writepos, inq, maxq, frag;
830                 if (dsound->hwbuf) {
831                         hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, &writepos);
832                         if (hres) {
833                             RtlReleaseResource(&(dsound->lock));
834                             return;
835                         }
836                         /* Well, we *could* do Just-In-Time mixing using the writepos,
837                          * but that's a little bit ambitious and unnecessary... */
838                         /* rather add our safety margin to the writepos, if we're playing */
839                         if (!paused) {
840                                 writepos += dsound->writelead;
841                                 while (writepos >= dsound->buflen)
842                                         writepos -= dsound->buflen;
843                         } else writepos = playpos;
844                 }
845                 else {
846                         playpos = dsound->pwplay * dsound->fraglen;
847                         writepos = playpos;
848                         if (!paused) {
849                                 writepos += ds_hel_margin * dsound->fraglen;
850                                 while (writepos >= dsound->buflen)
851                                         writepos -= dsound->buflen;
852                         }
853                 }
854                 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld\n",
855                       playpos,writepos,dsound->playpos,dsound->mixpos);
856                 /* wipe out just-played sound data */
857                 if (playpos < dsound->playpos) {
858                         memset(dsound->buffer + dsound->playpos, nfiller, dsound->buflen - dsound->playpos);
859                         memset(dsound->buffer, nfiller, playpos);
860                 } else {
861                         memset(dsound->buffer + dsound->playpos, nfiller, playpos - dsound->playpos);
862                 }
863                 dsound->playpos = playpos;
864
865                 EnterCriticalSection(&(dsound->mixlock));
866
867                 /* reset mixing if necessary */
868                 DSOUND_CheckReset(dsound, writepos);
869
870                 /* check how much prebuffering is left */
871                 inq = dsound->mixpos;
872                 if (inq < writepos)
873                         inq += dsound->buflen;
874                 inq -= writepos;
875
876                 /* find the maximum we can prebuffer */
877                 if (!paused) {
878                         maxq = playpos;
879                         if (maxq < writepos)
880                                 maxq += dsound->buflen;
881                         maxq -= writepos;
882                 } else maxq = dsound->buflen;
883
884                 /* clip maxq to dsound->prebuf */
885                 frag = dsound->prebuf * dsound->fraglen;
886                 if (maxq > frag) maxq = frag;
887
888                 /* check for consistency */
889                 if (inq > maxq) {
890                         /* the playback position must have passed our last
891                          * mixed position, i.e. it's an underrun, or we have
892                          * nothing more to play */
893                         TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
894                         inq = 0;
895                         /* stop the playback now, to allow buffers to refill */
896                         if (dsound->state == STATE_PLAYING) {
897                                 dsound->state = STATE_STARTING;
898                         }
899                         else if (dsound->state == STATE_STOPPING) {
900                                 dsound->state = STATE_STOPPED;
901                         }
902                         else {
903                                 /* how can we have an underrun if we aren't playing? */
904                                 WARN("unexpected primary state (%ld)\n", dsound->state);
905                         }
906 #ifdef SYNC_CALLBACK
907                         /* DSOUND_callback may need this lock */
908                         LeaveCriticalSection(&(dsound->mixlock));
909 #endif
910                         DSOUND_PrimaryStop(dsound);
911 #ifdef SYNC_CALLBACK
912                         EnterCriticalSection(&(dsound->mixlock));
913 #endif
914                         if (dsound->hwbuf) {
915                                 /* the Stop is supposed to reset play position to beginning of buffer */
916                                 /* unfortunately, OSS is not able to do so, so get current pointer */
917                                 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, NULL);
918                                 if (hres) {
919                                         LeaveCriticalSection(&(dsound->mixlock));
920                                         RtlReleaseResource(&(dsound->lock));
921                                         return;
922                                 }
923                         } else {
924                                 playpos = dsound->pwplay * dsound->fraglen;
925                         }
926                         writepos = playpos;
927                         dsound->playpos = playpos;
928                         dsound->mixpos = writepos;
929                         inq = 0;
930                         maxq = dsound->buflen;
931                         if (maxq > frag) maxq = frag;
932                         memset(dsound->buffer, nfiller, dsound->buflen);
933                         paused = TRUE;
934                 }
935
936                 /* do the mixing */
937                 frag = DSOUND_MixToPrimary(playpos, writepos, maxq, paused);
938                 if (forced) frag = maxq - inq;
939                 dsound->mixpos += frag;
940                 while (dsound->mixpos >= dsound->buflen)
941                         dsound->mixpos -= dsound->buflen;
942
943                 if (frag) {
944                         /* buffers have been filled, restart playback */
945                         if (dsound->state == STATE_STARTING) {
946                                 dsound->state = STATE_PLAYING;
947                         }
948                         else if (dsound->state == STATE_STOPPED) {
949                                 /* the dsound is supposed to play if there's something to play
950                                  * even if it is reported as stopped, so don't let this confuse you */
951                                 dsound->state = STATE_STOPPING;
952                         }
953                         LeaveCriticalSection(&(dsound->mixlock));
954                         if (paused) {
955                                 DSOUND_PrimaryPlay(dsound);
956                                 TRACE("starting playback\n");
957                         }
958                 }
959                 else
960                         LeaveCriticalSection(&(dsound->mixlock));
961         } else {
962                 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
963                 if (dsound->state == STATE_STARTING) {
964                         DSOUND_PrimaryPlay(dsound);
965                         dsound->state = STATE_PLAYING;
966                 }
967                 else if (dsound->state == STATE_STOPPING) {
968                         DSOUND_PrimaryStop(dsound);
969                         dsound->state = STATE_STOPPED;
970                 }
971         }
972         TRACE("completed processing at %ld\n", GetTickCount());
973         RtlReleaseResource(&(dsound->lock));
974 }
975
976 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
977 {
978         if (!dsound) {
979                 ERR("dsound died without killing us?\n");
980                 timeKillEvent(timerID);
981                 timeEndPeriod(DS_TIME_RES);
982                 return;
983         }
984
985         TRACE("entered\n");
986         DSOUND_PerformMix();
987 }
988
989 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
990 {
991         IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
992         TRACE("entering at %ld, msg=%08x(%s)\n", GetTickCount(), msg, 
993                 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" : 
994                 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
995         if (msg == MM_WOM_DONE) {
996                 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
997                 if (This->pwqueue == (DWORD)-1) {
998                         TRACE("completed due to reset\n");
999                         return;
1000                 }
1001 /* it could be a bad idea to enter critical section here... if there's lock contention,
1002  * the resulting scheduling delays might obstruct the winmm player thread */
1003 #ifdef SYNC_CALLBACK
1004                 EnterCriticalSection(&(This->mixlock));
1005 #endif
1006                 /* retrieve current values */
1007                 fraglen = dsound->fraglen;
1008                 buflen = dsound->buflen;
1009                 pwplay = dsound->pwplay;
1010                 playpos = pwplay * fraglen;
1011                 mixpos = dsound->mixpos;
1012                 /* check remaining mixed data */
1013                 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1014                 mixq = inq / fraglen;
1015                 if ((inq - (mixq * fraglen)) > 0) mixq++;
1016                 /* complete the playing buffer */
1017                 TRACE("done playing primary pos=%ld\n", playpos);
1018                 pwplay++;
1019                 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1020                 /* write new values */
1021                 dsound->pwplay = pwplay;
1022                 dsound->pwqueue--;
1023                 /* queue new buffer if we have data for it */
1024                 if (inq>1) DSOUND_WaveQueue(This, inq-1);
1025 #ifdef SYNC_CALLBACK
1026                 LeaveCriticalSection(&(This->mixlock));
1027 #endif
1028         }
1029         TRACE("completed\n");
1030 }