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