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