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