Change some functions arguments from () -> (void).
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include <assert.h>
23 #include <stdarg.h>
24 #include <math.h>       /* Insomnia - pow() function */
25
26 #define NONAMELESSSTRUCT
27 #define NONAMELESSUNION
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winuser.h"
31 #include "mmsystem.h"
32 #include "winreg.h"
33 #include "winternl.h"
34 #include "wine/debug.h"
35 #include "dsound.h"
36 #include "dsdriver.h"
37 #include "dsound_private.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
40
41 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
42 {
43         double temp;
44         TRACE("(%p)\n",volpan);
45
46         TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
47         /* the AmpFactors are expressed in 16.16 fixed point */
48         volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
49         /* FIXME: dwPan{Left|Right}AmpFactor */
50
51         /* FIXME: use calculated vol and pan ampfactors */
52         temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
53         volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
54         temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
55         volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
56
57         TRACE("left = %x, right = %x\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
58 }
59
60 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
61 {
62     double left,right;
63     TRACE("(%p)\n",volpan);
64
65     TRACE("left=%x, right=%x\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
66     if (volpan->dwTotalLeftAmpFactor==0)
67         left=-10000;
68     else
69         left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
70     if (volpan->dwTotalRightAmpFactor==0)
71         right=-10000;
72     else
73         right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
74     if (left<right)
75     {
76         volpan->lVolume=right;
77         volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
78     }
79     else
80     {
81         volpan->lVolume=left;
82         volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
83     }
84     if (volpan->lVolume < -10000)
85         volpan->lVolume=-10000;
86     volpan->lPan=right-left;
87     if (volpan->lPan < -10000)
88         volpan->lPan=-10000;
89
90     TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
91 }
92
93 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
94 {
95         TRACE("(%p)\n",dsb);
96
97         /* calculate the 10ms write lead */
98         dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
99 }
100
101 /**
102  * Check for application callback requests for when the play position
103  * reaches certain points.
104  *
105  * The offsets that will be triggered will be those between the recorded
106  * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
107  * beyond that position.
108  */
109 void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len)
110 {
111         int                     i;
112         DWORD                   offset;
113         LPDSBPOSITIONNOTIFY     event;
114         TRACE("(%p,%d)\n",dsb,len);
115
116         if (dsb->nrofnotifies == 0)
117                 return;
118
119         TRACE("(%p) buflen = %d, playpos = %d, len = %d\n",
120                 dsb, dsb->buflen, dsb->playpos, len);
121         for (i = 0; i < dsb->nrofnotifies ; i++) {
122                 event = dsb->notifies + i;
123                 offset = event->dwOffset;
124                 TRACE("checking %d, position %d, event = %p\n",
125                         i, offset, event->hEventNotify);
126                 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
127                 /* OK. [Inside DirectX, p274] */
128                 /*  */
129                 /* This also means we can't sort the entries by offset, */
130                 /* because DSBPN_OFFSETSTOP == -1 */
131                 if (offset == DSBPN_OFFSETSTOP) {
132                         if (dsb->state == STATE_STOPPED) {
133                                 SetEvent(event->hEventNotify);
134                                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
135                                 return;
136                         } else
137                                 return;
138                 }
139                 if ((dsb->playpos + len) >= dsb->buflen) {
140                         if ((offset < ((dsb->playpos + len) % dsb->buflen)) ||
141                             (offset >= dsb->playpos)) {
142                                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
143                                 SetEvent(event->hEventNotify);
144                         }
145                 } else {
146                         if ((offset >= dsb->playpos) && (offset < (dsb->playpos + len))) {
147                                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
148                                 SetEvent(event->hEventNotify);
149                         }
150                 }
151         }
152 }
153
154 /* WAV format info can be found at:
155  *
156  *    http://www.cwi.nl/ftp/audio/AudioFormats.part2
157  *    ftp://ftp.cwi.nl/pub/audio/RIFF-format
158  *
159  * Import points to remember:
160  *    8-bit WAV is unsigned
161  *    16-bit WAV is signed
162  */
163  /* Use the same formulas as pcmconverter.c */
164 static inline INT16 cvtU8toS16(BYTE b)
165 {
166     return (short)((b+(b << 8))-32768);
167 }
168
169 static inline BYTE cvtS16toU8(INT16 s)
170 {
171     return (s >> 8) ^ (unsigned char)0x80;
172 }
173
174 /**
175  * Copy a single frame from the given input buffer to the given output buffer.
176  * Translate 8 <-> 16 bits and mono <-> stereo
177  */
178 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, BYTE *ibuf, BYTE *obuf )
179 {
180         DirectSoundDevice * device = dsb->device;
181         INT fl,fr;
182
183         if (dsb->pwfx->wBitsPerSample == 8)  {
184                 if (device->pwfx->wBitsPerSample == 8 &&
185                     device->pwfx->nChannels == dsb->pwfx->nChannels) {
186                         /* avoid needless 8->16->8 conversion */
187                         *obuf=*ibuf;
188                         if (dsb->pwfx->nChannels==2)
189                                 *(obuf+1)=*(ibuf+1);
190                         return;
191                 }
192                 fl = cvtU8toS16(*ibuf);
193                 fr = (dsb->pwfx->nChannels==2 ? cvtU8toS16(*(ibuf + 1)) : fl);
194         } else {
195                 fl = *((INT16 *)ibuf);
196                 fr = (dsb->pwfx->nChannels==2 ? *(((INT16 *)ibuf) + 1)  : fl);
197         }
198
199         if (device->pwfx->nChannels == 2) {
200                 if (device->pwfx->wBitsPerSample == 8) {
201                         *obuf = cvtS16toU8(fl);
202                         *(obuf + 1) = cvtS16toU8(fr);
203                         return;
204                 }
205                 if (device->pwfx->wBitsPerSample == 16) {
206                         *((INT16 *)obuf) = fl;
207                         *(((INT16 *)obuf) + 1) = fr;
208                         return;
209                 }
210         }
211         if (device->pwfx->nChannels == 1) {
212                 fl = (fl + fr) >> 1;
213                 if (device->pwfx->wBitsPerSample == 8) {
214                         *obuf = cvtS16toU8(fl);
215                         return;
216                 }
217                 if (device->pwfx->wBitsPerSample == 16) {
218                         *((INT16 *)obuf) = fl;
219                         return;
220                 }
221         }
222 }
223
224 /**
225  * Mix at most the given amount of data into the given device buffer from the
226  * given secondary buffer, starting from the dsb's first currently unmixed
227  * frame (buf_mixpos), translating frequency (pitch), stereo/mono and
228  * bits-per-sample. The secondary buffer sample is looped if it is not
229  * long enough and it is a looping buffer.
230  * (Doesn't perform any mixing - this is a straight copy operation).
231  *
232  * Now with PerfectPitch (tm) technology
233  *
234  * dsb = the secondary buffer
235  * buf = the device buffer
236  * len = number of bytes to store in the device buffer
237  *
238  * Returns: the number of bytes read from the secondary buffer
239  *   (ie. len, adjusted for frequency, number of channels and sample size,
240  *    and limited by buffer length for non-looping buffers)
241  */
242 static INT DSOUND_MixerNorm(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
243 {
244         INT     i, size, ipos, ilen;
245         BYTE    *ibp, *obp;
246         INT     iAdvance = dsb->pwfx->nBlockAlign;
247         INT     oAdvance = dsb->device->pwfx->nBlockAlign;
248
249         ibp = dsb->buffer->memory + dsb->buf_mixpos;
250         obp = buf;
251
252         TRACE("(%p, %p, %p), buf_mixpos=%d\n", dsb, ibp, obp, dsb->buf_mixpos);
253         /* Check for the best case */
254         if ((dsb->freq == dsb->device->pwfx->nSamplesPerSec) &&
255             (dsb->pwfx->wBitsPerSample == dsb->device->pwfx->wBitsPerSample) &&
256             (dsb->pwfx->nChannels == dsb->device->pwfx->nChannels)) {
257                 INT bytesleft = dsb->buflen - dsb->buf_mixpos;
258                 TRACE("(%p) Best case\n", dsb);
259                 if (len <= bytesleft )
260                         CopyMemory(obp, ibp, len);
261                 else { /* wrap */
262                         CopyMemory(obp, ibp, bytesleft);
263                         CopyMemory(obp + bytesleft, dsb->buffer->memory, len - bytesleft);
264                 }
265                 return len;
266         }
267
268         /* Check for same sample rate */
269         if (dsb->freq == dsb->device->pwfx->nSamplesPerSec) {
270                 TRACE("(%p) Same sample rate %d = primary %d\n", dsb,
271                         dsb->freq, dsb->device->pwfx->nSamplesPerSec);
272                 ilen = 0;
273                 for (i = 0; i < len; i += oAdvance) {
274                         cp_fields(dsb, ibp, obp );
275                         ibp += iAdvance;
276                         ilen += iAdvance;
277                         obp += oAdvance;
278                         if (ibp >= (BYTE *)(dsb->buffer->memory + dsb->buflen))
279                                 ibp = dsb->buffer->memory;      /* wrap */
280                 }
281                 return (ilen);
282         }
283
284         /* Mix in different sample rates */
285         /* */
286         /* New PerfectPitch(tm) Technology (c) 1998 Rob Riggs */
287         /* Patent Pending :-] */
288
289         /* Patent enhancements (c) 2000 Ove KÃ¥ven,
290          * TransGaming Technologies Inc. */
291
292         /* FIXME("(%p) Adjusting frequency: %ld -> %ld (need optimization)\n",
293            dsb, dsb->freq, dsb->device->pwfx->nSamplesPerSec); */
294
295         size = len / oAdvance;
296         ilen = 0;
297         ipos = dsb->buf_mixpos;
298         for (i = 0; i < size; i++) {
299                 cp_fields(dsb, (dsb->buffer->memory + ipos), obp);
300                 obp += oAdvance;
301                 dsb->freqAcc += dsb->freqAdjust;
302                 if (dsb->freqAcc >= (1<<DSOUND_FREQSHIFT)) {
303                         ULONG adv = (dsb->freqAcc>>DSOUND_FREQSHIFT) * iAdvance;
304                         dsb->freqAcc &= (1<<DSOUND_FREQSHIFT)-1;
305                         ipos += adv; ilen += adv;
306                         ipos %= dsb->buflen;
307                 }
308         }
309         return ilen;
310 }
311
312 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
313 {
314         INT     i;
315         BYTE    *bpc = buf;
316         INT16   *bps = (INT16 *) buf;
317
318         TRACE("(%p,%p,%d)\n",dsb,buf,len);
319         TRACE("left = %x, right = %x\n", dsb->cvolpan.dwTotalLeftAmpFactor,
320                 dsb->cvolpan.dwTotalRightAmpFactor);
321
322         if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->cvolpan.lPan == 0)) &&
323             (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->cvolpan.lVolume == 0)) &&
324             !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
325                 return;         /* Nothing to do */
326
327         /* If we end up with some bozo coder using panning or 3D sound */
328         /* with a mono primary buffer, it could sound very weird using */
329         /* this method. Oh well, tough patooties. */
330
331         switch (dsb->device->pwfx->wBitsPerSample) {
332         case 8:
333                 /* 8-bit WAV is unsigned, but we need to operate */
334                 /* on signed data for this to work properly */
335                 switch (dsb->device->pwfx->nChannels) {
336                 case 1:
337                         for (i = 0; i < len; i++) {
338                                 INT val = *bpc - 128;
339                                 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
340                                 *bpc = val + 128;
341                                 bpc++;
342                         }
343                         break;
344                 case 2:
345                         for (i = 0; i < len; i+=2) {
346                                 INT val = *bpc - 128;
347                                 val = (val * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
348                                 *bpc++ = val + 128;
349                                 val = *bpc - 128;
350                                 val = (val * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
351                                 *bpc = val + 128;
352                                 bpc++;
353                         }
354                         break;
355                 default:
356                         FIXME("doesn't support %d channels\n", dsb->device->pwfx->nChannels);
357                         break;
358                 }
359                 break;
360         case 16:
361                 /* 16-bit WAV is signed -- much better */
362                 switch (dsb->device->pwfx->nChannels) {
363                 case 1:
364                         for (i = 0; i < len; i += 2) {
365                                 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
366                                 bps++;
367                         }
368                         break;
369                 case 2:
370                         for (i = 0; i < len; i += 4) {
371                                 *bps = (*bps * dsb->cvolpan.dwTotalLeftAmpFactor) >> 16;
372                                 bps++;
373                                 *bps = (*bps * dsb->cvolpan.dwTotalRightAmpFactor) >> 16;
374                                 bps++;
375                         }
376                         break;
377                 default:
378                         FIXME("doesn't support %d channels\n", dsb->device->pwfx->nChannels);
379                         break;
380                 }
381                 break;
382         default:
383                 FIXME("doesn't support %d bit samples\n", dsb->device->pwfx->wBitsPerSample);
384                 break;
385         }
386 }
387
388 /**
389  * Make sure the device's tmp_buffer is at least the given size. Return a
390  * pointer to it.
391  */
392 static LPBYTE DSOUND_tmpbuffer(DirectSoundDevice *device, DWORD len)
393 {
394     TRACE("(%p,%d)\n", device, len);
395
396     if (len > device->tmp_buffer_len) {
397         if (device->tmp_buffer)
398             device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, device->tmp_buffer, len);
399         else
400             device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
401
402         device->tmp_buffer_len = len;
403     }
404
405     return device->tmp_buffer;
406 }
407
408 /**
409  * Mix (at most) the given number of bytes into the given position of the
410  * device buffer, from the secondary buffer "dsb" (starting at the current
411  * mix position for that buffer).
412  *
413  * Returns the number of bytes actually mixed into the device buffer. This
414  * will match fraglen unless the end of the secondary buffer is reached
415  * (and it is not looping).
416  *
417  * dsb  = the secondary buffer to mix from
418  * writepos = position (offset) in device buffer to write at
419  * fraglen = number of bytes to mix
420  */
421 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
422 {
423         INT     i, len, ilen, field, todo;
424         BYTE    *buf, *ibuf;
425
426         TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
427
428         len = fraglen;
429         if (!(dsb->playflags & DSBPLAY_LOOPING)) {
430                 /* This buffer is not looping, so make sure the requested
431                  * length will not take us past the end of the buffer */
432                 int secondary_remainder = dsb->buflen - dsb->buf_mixpos;
433                 int adjusted_remainder = MulDiv(dsb->device->pwfx->nAvgBytesPerSec, secondary_remainder, dsb->nAvgBytesPerSec);
434                 assert(adjusted_remainder >= 0);
435                         /* The adjusted remainder must be at least one sample,
436                          * otherwise we will never reach the end of the
437                          * secondary buffer, as there will perpetually be a
438                          * fractional remainder */
439                 TRACE("secondary_remainder = %d, adjusted_remainder = %d, len = %d\n", secondary_remainder, adjusted_remainder, len);
440                 if (adjusted_remainder < len) {
441                         TRACE("clipping len to remainder of secondary buffer\n");
442                         len = adjusted_remainder;
443                 }
444                 if (len == 0)
445                         return 0;
446         }
447
448         if (len % dsb->device->pwfx->nBlockAlign) {
449                 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
450                 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
451                 len = (len / nBlockAlign) * nBlockAlign;        /* data alignment */
452         }
453
454         if ((buf = ibuf = DSOUND_tmpbuffer(dsb->device, len)) == NULL)
455                 return 0;
456
457         TRACE("MixInBuffer (%p) len = %d, dest = %d\n", dsb, len, writepos);
458
459         /* first, copy the data from the DirectSoundBuffer into the temporary
460            buffer, translating frequency/bits-per-sample/number-of-channels
461            to match the device settings */
462         ilen = DSOUND_MixerNorm(dsb, ibuf, len);
463         if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
464             (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
465             (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
466                 DSOUND_MixerVol(dsb, ibuf, len);
467
468         /* Now mix the temporary buffer into the devices main buffer */
469         if (dsb->device->pwfx->wBitsPerSample == 8) {
470                 BYTE    *obuf = dsb->device->buffer + writepos;
471
472                 if ((writepos + len) <= dsb->device->buflen)
473                         todo = len;
474                 else
475                         todo = dsb->device->buflen - writepos;
476
477                 for (i = 0; i < todo; i++) {
478                         /* 8-bit WAV is unsigned */
479                         field = (*ibuf++ - 128);
480                         field += (*obuf - 128);
481                         if (field > 127) field = 127;
482                         else if (field < -128) field = -128;
483                         *obuf++ = field + 128;
484                 }
485  
486                 if (todo < len) {
487                         todo = len - todo;
488                         obuf = dsb->device->buffer;
489
490                         for (i = 0; i < todo; i++) {
491                                 /* 8-bit WAV is unsigned */
492                                 field = (*ibuf++ - 128);
493                                 field += (*obuf - 128);
494                                 if (field > 127) field = 127;
495                                 else if (field < -128) field = -128;
496                                 *obuf++ = field + 128;
497                         }
498                 }
499         } else {
500                 INT16   *ibufs, *obufs;
501
502                 ibufs = (INT16 *) ibuf;
503                 obufs = (INT16 *)(dsb->device->buffer + writepos);
504
505                 if ((writepos + len) <= dsb->device->buflen)
506                         todo = len / 2;
507                 else
508                         todo = (dsb->device->buflen - writepos) / 2;
509
510                 for (i = 0; i < todo; i++) {
511                         /* 16-bit WAV is signed */
512                         field = *ibufs++;
513                         field += *obufs;
514                         if (field > 32767) field = 32767;
515                         else if (field < -32768) field = -32768;
516                         *obufs++ = field;
517                 }
518
519                 if (todo < (len / 2)) {
520                         todo = (len / 2) - todo;
521                         obufs = (INT16 *)dsb->device->buffer;
522
523                         for (i = 0; i < todo; i++) {
524                                 /* 16-bit WAV is signed */
525                                 field = *ibufs++;
526                                 field += *obufs;
527                                 if (field > 32767) field = 32767;
528                                 else if (field < -32768) field = -32768;
529                                 *obufs++ = field;
530                         }
531                 }
532         }
533
534         if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
535                 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
536                  * not the MIX position... but if the sound buffer is bigger than our prebuffering
537                  * (which must be the case for the streaming buffers that need this hack anyway)
538                  * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
539                 dsb->leadin = FALSE;
540         }
541
542         dsb->buf_mixpos += ilen;
543
544         if (dsb->buf_mixpos >= dsb->buflen) {
545                 if (dsb->playflags & DSBPLAY_LOOPING) {
546                         /* wrap */
547                         dsb->buf_mixpos %= dsb->buflen;
548                         if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
549                                 dsb->leadin = FALSE; /* HACK: see above */
550                 } else if (dsb->buf_mixpos > dsb->buflen) {
551                         ERR("Mixpos (%u) past buflen (%u), capping...\n", dsb->buf_mixpos, dsb->buflen);
552                         dsb->buf_mixpos = dsb->buflen;
553                 }
554         }
555
556         return len;
557 }
558
559 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
560 {
561         INT     ilen, field;
562         UINT    i, todo;
563         BYTE    *buf, *ibuf;
564
565         TRACE("(%p,%d,%d)\n",dsb,writepos,len);
566
567         if (len % dsb->device->pwfx->nBlockAlign) {
568                 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
569                 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
570                 len = (len / nBlockAlign) * nBlockAlign;        /* data alignment */
571         }
572
573         if ((buf = ibuf = DSOUND_tmpbuffer(dsb->device, len)) == NULL)
574                 return;
575
576         TRACE("PhaseCancel (%p) len = %d, dest = %d\n", dsb, len, writepos);
577
578         ilen = DSOUND_MixerNorm(dsb, ibuf, len);
579         if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
580             (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
581             (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
582                 DSOUND_MixerVol(dsb, ibuf, len);
583
584         /* subtract instead of add, to phase out premixed data */
585         if (dsb->device->pwfx->wBitsPerSample == 8) {
586                 BYTE    *obuf = dsb->device->buffer + writepos;
587
588                 if ((writepos + len) <= dsb->device->buflen)
589                         todo = len;
590                 else
591                         todo = dsb->device->buflen - writepos;
592
593                 for (i = 0; i < todo; i++) {
594                         /* 8-bit WAV is unsigned */
595                         field = (*obuf - 128);
596                         field -= (*ibuf++ - 128);
597                         if (field > 127) field = 127;
598                         else if (field < -128) field = -128;
599                         *obuf++ = field + 128;
600                 }
601  
602                 if (todo < len) {
603                         todo = len - todo;
604                         obuf = dsb->device->buffer;
605
606                         for (i = 0; i < todo; i++) {
607                                 /* 8-bit WAV is unsigned */
608                                 field = (*obuf - 128);
609                                 field -= (*ibuf++ - 128);
610                                 if (field > 127) field = 127;
611                                 else if (field < -128) field = -128;
612                                 *obuf++ = field + 128;
613                         }
614                 }
615         } else {
616                 INT16   *ibufs, *obufs;
617
618                 ibufs = (INT16 *) ibuf;
619                 obufs = (INT16 *)(dsb->device->buffer + writepos);
620
621                 if ((writepos + len) <= dsb->device->buflen)
622                         todo = len / 2;
623                 else
624                         todo = (dsb->device->buflen - writepos) / 2;
625
626                 for (i = 0; i < todo; i++) {
627                         /* 16-bit WAV is signed */
628                         field = *obufs;
629                         field -= *ibufs++;
630                         if (field > 32767) field = 32767;
631                         else if (field < -32768) field = -32768;
632                         *obufs++ = field;
633                 }
634
635                 if (todo < (len / 2)) {
636                         todo = (len / 2) - todo;
637                         obufs = (INT16 *)dsb->device->buffer;
638
639                         for (i = 0; i < todo; i++) {
640                                 /* 16-bit WAV is signed */
641                                 field = *obufs;
642                                 field -= *ibufs++;
643                                 if (field > 32767) field = 32767;
644                                 else if (field < -32768) field = -32768;
645                                 *obufs++ = field;
646                         }
647                 }
648         }
649 }
650
651 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
652 {
653         DWORD   size, flen, len, npos, nlen;
654         INT     iAdvance = dsb->pwfx->nBlockAlign;
655         INT     oAdvance = dsb->device->pwfx->nBlockAlign;
656         /* determine amount of premixed data to cancel */
657         DWORD primary_done =
658                 ((dsb->primary_mixpos < writepos) ? dsb->device->buflen : 0) +
659                 dsb->primary_mixpos - writepos;
660
661         TRACE("(%p, %d), buf_mixpos=%d\n", dsb, writepos, dsb->buf_mixpos);
662
663         /* backtrack the mix position */
664         size = primary_done / oAdvance;
665         flen = size * dsb->freqAdjust;
666         len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
667         flen &= (1<<DSOUND_FREQSHIFT)-1;
668         while (dsb->freqAcc < flen) {
669                 len += iAdvance;
670                 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
671         }
672         len %= dsb->buflen;
673         npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
674                 dsb->buf_mixpos - len;
675         if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
676                 /* stop backtracking at startpos */
677                 npos = dsb->startpos;
678                 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
679                         dsb->buf_mixpos - npos;
680                 flen = dsb->freqAcc;
681                 nlen = len / dsb->pwfx->nBlockAlign;
682                 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
683                 nlen *= dsb->device->pwfx->nBlockAlign;
684                 writepos =
685                         ((dsb->primary_mixpos < nlen) ? dsb->device->buflen : 0) +
686                         dsb->primary_mixpos - nlen;
687         }
688
689         dsb->freqAcc -= flen;
690         dsb->buf_mixpos = npos;
691         dsb->primary_mixpos = writepos;
692
693         TRACE("new buf_mixpos=%d, primary_mixpos=%d (len=%d)\n",
694               dsb->buf_mixpos, dsb->primary_mixpos, len);
695
696         if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
697 }
698
699 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
700 {
701 #if 0
702         DWORD   i, size, flen, len, npos, nlen;
703         INT     iAdvance = dsb->pwfx->nBlockAlign;
704         INT     oAdvance = dsb->device->pwfx->nBlockAlign;
705         /* determine amount of premixed data to cancel */
706         DWORD buf_done =
707                 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
708                 dsb->buf_mixpos - buf_writepos;
709 #endif
710
711         WARN("(%p, %d), buf_mixpos=%d\n", dsb, buf_writepos, dsb->buf_mixpos);
712         /* since this is not implemented yet, just cancel *ALL* prebuffering for now
713          * (which is faster anyway when there's only a single secondary buffer) */
714         dsb->device->need_remix = TRUE;
715 }
716
717 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
718 {
719         TRACE("(%p)\n",dsb);
720         EnterCriticalSection(&dsb->lock);
721         if (dsb->state == STATE_PLAYING)
722                 dsb->device->need_remix = TRUE;
723         LeaveCriticalSection(&dsb->lock);
724 }
725
726 /**
727  * Calculate the distance between two buffer offsets, taking wraparound
728  * into account.
729  */
730 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
731 {
732         if (ptr1 >= ptr2) {
733                 return ptr1 - ptr2;
734         } else {
735                 return buflen + ptr1 - ptr2;
736         }
737 }
738
739 /**
740  * Mix some frames from the given secondary buffer "dsb" into the device
741  * primary buffer.
742  *
743  * dsb = the secondary buffer
744  * playpos = the current play position in the device buffer (primary buffer)
745  * writepos = the current safe-to-write position in the device buffer
746  * mixlen = the maximum number of bytes in the primary buffer to mix, from the
747  *          current writepos.
748  *
749  * Returns: the number of bytes beyond the writepos that were mixed.
750  */
751 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
752 {
753         /* The buffer's primary_mixpos may be before or after the the device
754          * buffer's mixpos, but both must be ahead of writepos. */
755
756         DWORD len, slen;
757         /* determine this buffer's write position */
758         DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, writepos, writepos);
759         /* determine how much already-mixed data exists */
760         DWORD buf_done = DSOUND_BufPtrDiff(dsb->buflen, dsb->buf_mixpos, buf_writepos);
761         DWORD primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
762         DWORD adv_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->device->mixpos, writepos);
763         DWORD played = DSOUND_BufPtrDiff(dsb->buflen, buf_writepos, dsb->playpos);
764         DWORD buf_left = dsb->buflen - buf_writepos;
765         int still_behind;
766
767         TRACE("(%p,%d,%d,%d)\n",dsb,playpos,writepos,mixlen);
768         TRACE("buf_writepos=%d, primary_writepos=%d\n", buf_writepos, writepos);
769         TRACE("buf_done=%d, primary_done=%d\n", buf_done, primary_done);
770         TRACE("buf_mixpos=%d, primary_mixpos=%d, mixlen=%d\n", dsb->buf_mixpos, dsb->primary_mixpos,
771               mixlen);
772         TRACE("looping=%d, startpos=%d, leadin=%d\n", dsb->playflags, dsb->startpos, dsb->leadin);
773
774         /* check for notification positions */
775         if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
776             dsb->state != STATE_STARTING) {
777                 DSOUND_CheckEvent(dsb, played);
778         }
779
780         /* save write position for non-GETCURRENTPOSITION2... */
781         dsb->playpos = buf_writepos;
782
783         /* check whether CalcPlayPosition detected a mixing underrun */
784         if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
785                 /* it did, but did we have more to play? */
786                 if ((dsb->playflags & DSBPLAY_LOOPING) ||
787                     (dsb->buf_mixpos < dsb->buflen)) {
788                         /* yes, have to recover */
789                         ERR("underrun on sound buffer %p\n", dsb);
790                         TRACE("recovering from underrun: primary_mixpos=%d\n", writepos);
791                 }
792                 dsb->primary_mixpos = writepos;
793                 primary_done = 0;
794         }
795         /* determine how far ahead we should mix */
796         if (((dsb->playflags & DSBPLAY_LOOPING) ||
797              (dsb->leadin && (dsb->probably_valid_to != 0))) &&
798             !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
799                 /* if this is a streaming buffer, it typically means that
800                  * we should defer mixing past probably_valid_to as long
801                  * as we can, to avoid unnecessary remixing */
802                 /* the heavy-looking calculations shouldn't be that bad,
803                  * as any game isn't likely to be have more than 1 or 2
804                  * streaming buffers in use at any time anyway... */
805                 DWORD probably_valid_left =
806                         (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
807                         ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
808                         dsb->probably_valid_to - buf_writepos;
809                 /* check for leadin condition */
810                 if ((probably_valid_left == 0) &&
811                     (dsb->probably_valid_to == dsb->startpos) &&
812                     dsb->leadin)
813                         probably_valid_left = dsb->buflen;
814                 TRACE("streaming buffer probably_valid_to=%d, probably_valid_left=%d\n",
815                       dsb->probably_valid_to, probably_valid_left);
816                 /* check whether the app's time is already up */
817                 if (probably_valid_left < dsb->writelead) {
818                         WARN("probably_valid_to now within writelead, possible streaming underrun\n");
819                         /* once we pass the point of no return,
820                          * no reason to hold back anymore */
821                         dsb->probably_valid_to = (DWORD)-1;
822                         /* we just have to go ahead and mix what we have,
823                          * there's no telling what the app is thinking anyway */
824                 } else {
825                         /* adjust for our frequency and our sample size */
826                         probably_valid_left = MulDiv(probably_valid_left,
827                                                      1 << DSOUND_FREQSHIFT,
828                                                      dsb->pwfx->nBlockAlign * dsb->freqAdjust) *
829                                               dsb->device->pwfx->nBlockAlign;
830                         /* check whether to clip mix_len */
831                         if (probably_valid_left < mixlen) {
832                                 TRACE("clipping to probably_valid_left=%d\n", probably_valid_left);
833                                 mixlen = probably_valid_left;
834                         }
835                 }
836         }
837         /* cut mixlen with what's already been mixed */
838         if (mixlen < primary_done) {
839                 /* huh? and still CalcPlayPosition didn't
840                  * detect an underrun? */
841                 FIXME("problem with underrun detection (mixlen=%d < primary_done=%d)\n", mixlen, primary_done);
842                 return 0;
843         }
844         len = mixlen - primary_done;
845         TRACE("remaining mixlen=%d\n", len);
846
847         if (len < dsb->device->fraglen) {
848                 /* smaller than a fragment, wait until it gets larger
849                  * before we take the mixing overhead */
850                 TRACE("mixlen not worth it, deferring mixing\n");
851                 still_behind = 1;
852                 goto post_mix;
853         }
854
855         /* ok, we know how much to mix, let's go */
856         still_behind = (adv_done > primary_done);
857         while (len) {
858                 slen = dsb->device->buflen - dsb->primary_mixpos;
859                 if (slen > len) slen = len;
860                 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
861
862                 if ((dsb->primary_mixpos < dsb->device->mixpos) &&
863                     (dsb->primary_mixpos + slen >= dsb->device->mixpos))
864                         still_behind = FALSE;
865
866                 dsb->primary_mixpos += slen; len -= slen;
867                 dsb->primary_mixpos %= dsb->device->buflen;
868
869                 if ((dsb->state == STATE_STOPPED) || !slen) break;
870         }
871         TRACE("new primary_mixpos=%d, primary_advbase=%d\n", dsb->primary_mixpos, dsb->device->mixpos);
872         TRACE("mixed data len=%d, still_behind=%d\n", mixlen-len, still_behind);
873
874 post_mix:
875         /* check if buffer should be considered complete */
876         if (buf_left < dsb->writelead &&
877             !(dsb->playflags & DSBPLAY_LOOPING)) {
878                 dsb->state = STATE_STOPPED;
879                 dsb->playpos = 0;
880                 dsb->last_playpos = 0;
881                 dsb->buf_mixpos = 0;
882                 dsb->leadin = FALSE;
883                 dsb->need_remix = FALSE;
884                 DSOUND_CheckEvent(dsb, buf_left);
885         }
886
887         /* return how far we think the primary buffer can
888          * advance its underrun detector...*/
889         if (still_behind) return 0;
890         if ((mixlen - len) < primary_done) return 0;
891         slen = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, dsb->device->mixpos);
892         if (slen > mixlen) {
893                 /* the primary_done and still_behind checks above should have worked */
894                 FIXME("problem with advancement calculation (advlen=%d > mixlen=%d)\n", slen, mixlen);
895                 slen = 0;
896         }
897         return slen;
898 }
899
900 /**
901  * For a DirectSoundDevice, go through all the currently playing buffers and
902  * mix them in to the device buffer.
903  *
904  * playpos = the current play position in the primary buffer
905  * writepos = the current safe-to-write position in the primary buffer
906  * mixlen = the maximum amount to mix into the primary buffer
907  *          (beyond the current writepos)
908  * recover = true if the sound device may have been reset and the write
909  *           position in the device buffer changed
910  *
911  * Returns:  the length beyond the writepos that was mixed to.
912  */
913 static DWORD DSOUND_MixToPrimary(DirectSoundDevice *device, DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
914 {
915         INT                     i, len, maxlen = 0;
916         IDirectSoundBufferImpl  *dsb;
917
918         TRACE("(%d,%d,%d,%d)\n", playpos, writepos, mixlen, recover);
919         for (i = 0; i < device->nrofbuffers; i++) {
920                 dsb = device->buffers[i];
921
922                 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
923                         TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
924                         EnterCriticalSection(&(dsb->lock));
925                         if (dsb->state == STATE_STOPPING) {
926                                 DSOUND_MixCancel(dsb, writepos, TRUE);
927                                 dsb->state = STATE_STOPPED;
928                                 DSOUND_CheckEvent(dsb, 0);
929                         } else {
930                                 if ((dsb->state == STATE_STARTING) || recover) {
931                                         dsb->primary_mixpos = writepos;
932                                         dsb->cvolpan = dsb->volpan;
933                                         dsb->need_remix = FALSE;
934                                 }
935                                 else if (dsb->need_remix) {
936                                         DSOUND_MixCancel(dsb, writepos, TRUE);
937                                         dsb->cvolpan = dsb->volpan;
938                                         dsb->need_remix = FALSE;
939                                 }
940                                 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
941                                 if (dsb->state == STATE_STARTING)
942                                         dsb->state = STATE_PLAYING;
943                                 maxlen = (len > maxlen) ? len : maxlen;
944                         }
945                         LeaveCriticalSection(&(dsb->lock));
946                 }
947         }
948
949         return maxlen;
950 }
951
952 static void DSOUND_MixReset(DirectSoundDevice *device, DWORD writepos)
953 {
954         INT                     i;
955         IDirectSoundBufferImpl  *dsb;
956         int nfiller;
957
958         TRACE("(%p,%d)\n", device, writepos);
959
960         /* the sound of silence */
961         nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
962
963         /* reset all buffer mix positions */
964         for (i = 0; i < device->nrofbuffers; i++) {
965                 dsb = device->buffers[i];
966
967                 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
968                         TRACE("Resetting %p\n", dsb);
969                         EnterCriticalSection(&(dsb->lock));
970                         if (dsb->state == STATE_STOPPING) {
971                                 dsb->state = STATE_STOPPED;
972                         }
973                         else if (dsb->state == STATE_STARTING) {
974                                 /* nothing */
975                         } else {
976                                 DSOUND_MixCancel(dsb, writepos, FALSE);
977                                 dsb->cvolpan = dsb->volpan;
978                                 dsb->need_remix = FALSE;
979                         }
980                         LeaveCriticalSection(&(dsb->lock));
981                 }
982         }
983
984         /* wipe out premixed data */
985         if (device->mixpos < writepos) {
986                 FillMemory(device->buffer + writepos, device->buflen - writepos, nfiller);
987                 FillMemory(device->buffer, device->mixpos, nfiller);
988         } else {
989                 FillMemory(device->buffer + writepos, device->mixpos - writepos, nfiller);
990         }
991
992         /* reset primary mix position */
993         device->mixpos = writepos;
994 }
995
996 static void DSOUND_CheckReset(DirectSoundDevice *device, DWORD writepos)
997 {
998         TRACE("(%p,%d)\n",device,writepos);
999         if (device->need_remix) {
1000                 DSOUND_MixReset(device, writepos);
1001                 device->need_remix = FALSE;
1002                 /* maximize Half-Life performance */
1003                 device->prebuf = ds_snd_queue_min;
1004                 device->precount = 0;
1005         } else {
1006                 device->precount++;
1007                 if (device->precount >= 4) {
1008                         if (device->prebuf < ds_snd_queue_max)
1009                                 device->prebuf++;
1010                         device->precount = 0;
1011                 }
1012         }
1013         TRACE("premix adjust: %d\n", device->prebuf);
1014 }
1015
1016 void DSOUND_WaveQueue(DirectSoundDevice *device, DWORD mixq)
1017 {
1018         TRACE("(%p,%d)\n", device, mixq);
1019         if (mixq + device->pwqueue > ds_hel_queue) mixq = ds_hel_queue - device->pwqueue;
1020         TRACE("queueing %d buffers, starting at %d\n", mixq, device->pwwrite);
1021         for (; mixq; mixq--) {
1022                 waveOutWrite(device->hwo, device->pwave[device->pwwrite], sizeof(WAVEHDR));
1023                 device->pwwrite++;
1024                 if (device->pwwrite >= DS_HEL_FRAGS) device->pwwrite = 0;
1025                 device->pwqueue++;
1026         }
1027 }
1028
1029 /* #define SYNC_CALLBACK */
1030
1031 /**
1032  * Perform mixing for a Direct Sound device. That is, go through all the
1033  * secondary buffers (the sound bites currently playing) and mix them in
1034  * to the primary buffer (the device buffer).
1035  */
1036 static void DSOUND_PerformMix(DirectSoundDevice *device)
1037 {
1038         int nfiller;
1039         BOOL forced;
1040         HRESULT hres;
1041
1042         TRACE("(%p)\n", device);
1043
1044         /* the sound of silence */
1045         nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
1046
1047         /* whether the primary is forced to play even without secondary buffers */
1048         forced = ((device->state == STATE_PLAYING) || (device->state == STATE_STARTING));
1049
1050         if (device->priolevel != DSSCL_WRITEPRIMARY) {
1051                 BOOL paused = ((device->state == STATE_STOPPED) || (device->state == STATE_STARTING));
1052                 /* FIXME: document variables */
1053                 DWORD playpos, writepos, inq, maxq, frag;
1054                 if (device->hwbuf) {
1055                         hres = IDsDriverBuffer_GetPosition(device->hwbuf, &playpos, &writepos);
1056                         if (hres) {
1057                             WARN("IDsDriverBuffer_GetPosition failed\n");
1058                             return;
1059                         }
1060                         /* Well, we *could* do Just-In-Time mixing using the writepos,
1061                          * but that's a little bit ambitious and unnecessary... */
1062                         /* rather add our safety margin to the writepos, if we're playing */
1063                         if (!paused) {
1064                                 writepos += device->writelead;
1065                                 writepos %= device->buflen;
1066                         } else writepos = playpos;
1067                 } else {
1068                         playpos = device->pwplay * device->fraglen;
1069                         writepos = playpos;
1070                         if (!paused) {
1071                                 writepos += ds_hel_margin * device->fraglen;
1072                                 writepos %= device->buflen;
1073                         }
1074                 }
1075                 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
1076                       playpos,writepos,device->playpos,device->mixpos,device->buflen);
1077                 assert(device->playpos < device->buflen);
1078                 /* wipe out just-played sound data */
1079                 if (playpos < device->playpos) {
1080                         FillMemory(device->buffer + device->playpos, device->buflen - device->playpos, nfiller);
1081                         FillMemory(device->buffer, playpos, nfiller);
1082                 } else {
1083                         FillMemory(device->buffer + device->playpos, playpos - device->playpos, nfiller);
1084                 }
1085                 device->playpos = playpos;
1086
1087                 EnterCriticalSection(&(device->mixlock));
1088
1089                 /* reset mixing if necessary */
1090                 DSOUND_CheckReset(device, writepos);
1091
1092                 /* check how much prebuffering is left */
1093                 inq = DSOUND_BufPtrDiff(device->buflen, device->mixpos, writepos);
1094
1095                 /* find the maximum we can prebuffer */
1096                 if (!paused)
1097                         maxq = DSOUND_BufPtrDiff(device->buflen, playpos, writepos);
1098                 /* If we get the whole buffer, difference is 0, so we need to set whole buffer then */
1099                 if (paused || !maxq)
1100                         maxq = device->buflen;
1101
1102                 /* clip maxq to device->prebuf */
1103                 frag = device->prebuf * device->fraglen;
1104                 if (maxq > frag)
1105                         maxq = frag;
1106
1107                 /* check for consistency */
1108                 if (inq > maxq) {
1109                         /* the playback position must have passed our last
1110                          * mixed position, i.e. it's an underrun, or we have
1111                          * nothing more to play */
1112                         TRACE("reached end of mixed data (inq=%d, maxq=%d)\n", inq, maxq);
1113                         inq = 0;
1114                         /* stop the playback now, to allow buffers to refill */
1115                         if (device->state == STATE_PLAYING) {
1116                                 device->state = STATE_STARTING;
1117                         }
1118                         else if (device->state == STATE_STOPPING) {
1119                                 device->state = STATE_STOPPED;
1120                         }
1121                         else {
1122                                 /* how can we have an underrun if we aren't playing? */
1123                                 WARN("unexpected primary state (%d)\n", device->state);
1124                         }
1125 #ifdef SYNC_CALLBACK
1126                         /* DSOUND_callback may need this lock */
1127                         LeaveCriticalSection(&(device->mixlock));
1128 #endif
1129                         if (DSOUND_PrimaryStop(device) != DS_OK)
1130                                 WARN("DSOUND_PrimaryStop failed\n");
1131 #ifdef SYNC_CALLBACK
1132                         EnterCriticalSection(&(device->mixlock));
1133 #endif
1134                         if (device->hwbuf) {
1135                                 /* the Stop is supposed to reset play position to beginning of buffer */
1136                                 /* unfortunately, OSS is not able to do so, so get current pointer */
1137                                 hres = IDsDriverBuffer_GetPosition(device->hwbuf, &playpos, NULL);
1138                                 if (hres) {
1139                                         LeaveCriticalSection(&(device->mixlock));
1140                                         WARN("IDsDriverBuffer_GetPosition failed\n");
1141                                         return;
1142                                 }
1143                         } else {
1144                                 playpos = device->pwplay * device->fraglen;
1145                         }
1146                         writepos = playpos;
1147                         device->playpos = playpos;
1148                         device->mixpos = writepos;
1149                         inq = 0;
1150                         maxq = device->buflen;
1151                         if (maxq > frag) maxq = frag;
1152                         FillMemory(device->buffer, device->buflen, nfiller);
1153                         paused = TRUE;
1154                 }
1155
1156                 /* do the mixing */
1157                 frag = DSOUND_MixToPrimary(device, playpos, writepos, maxq, paused);
1158                 if (forced) frag = maxq - inq;
1159                 device->mixpos += frag;
1160                 device->mixpos %= device->buflen;
1161
1162                 if (frag) {
1163                         /* buffers have been filled, restart playback */
1164                         if (device->state == STATE_STARTING) {
1165                                 device->state = STATE_PLAYING;
1166                         }
1167                         else if (device->state == STATE_STOPPED) {
1168                                 /* the dsound is supposed to play if there's something to play
1169                                  * even if it is reported as stopped, so don't let this confuse you */
1170                                 device->state = STATE_STOPPING;
1171                         }
1172                         LeaveCriticalSection(&(device->mixlock));
1173                         if (paused) {
1174                                 if (DSOUND_PrimaryPlay(device) != DS_OK)
1175                                         WARN("DSOUND_PrimaryPlay failed\n");
1176                                 else
1177                                         TRACE("starting playback\n");
1178                         }
1179                 }
1180                 else
1181                         LeaveCriticalSection(&(device->mixlock));
1182         } else {
1183                 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
1184                 if (device->state == STATE_STARTING) {
1185                         if (DSOUND_PrimaryPlay(device) != DS_OK)
1186                                 WARN("DSOUND_PrimaryPlay failed\n");
1187                         else
1188                                 device->state = STATE_PLAYING;
1189                 }
1190                 else if (device->state == STATE_STOPPING) {
1191                         if (DSOUND_PrimaryStop(device) != DS_OK)
1192                                 WARN("DSOUND_PrimaryStop failed\n");
1193                         else
1194                                 device->state = STATE_STOPPED;
1195                 }
1196         }
1197 }
1198
1199 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD_PTR dwUser,
1200                            DWORD_PTR dw1, DWORD_PTR dw2)
1201 {
1202         DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
1203         DWORD start_time =  GetTickCount();
1204         DWORD end_time;
1205         TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
1206         TRACE("entering at %d\n", start_time);
1207
1208         if (DSOUND_renderer[device->drvdesc.dnDevNode] != device) {
1209                 ERR("dsound died without killing us?\n");
1210                 timeKillEvent(timerID);
1211                 timeEndPeriod(DS_TIME_RES);
1212                 return;
1213         }
1214
1215         RtlAcquireResourceShared(&(device->buffer_list_lock), TRUE);
1216
1217         if (device->ref)
1218                 DSOUND_PerformMix(device);
1219
1220         RtlReleaseResource(&(device->buffer_list_lock));
1221
1222         end_time = GetTickCount();
1223         TRACE("completed processing at %d, duration = %d\n", end_time, end_time - start_time);
1224 }
1225
1226 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1227 {
1228         DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
1229         TRACE("(%p,%x,%x,%x,%x)\n",hwo,msg,dwUser,dw1,dw2);
1230         TRACE("entering at %d, msg=%08x(%s)\n", GetTickCount(), msg,
1231                 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" : 
1232                 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1233         if (msg == MM_WOM_DONE) {
1234                 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
1235                 if (device->pwqueue == (DWORD)-1) {
1236                         TRACE("completed due to reset\n");
1237                         return;
1238                 }
1239 /* it could be a bad idea to enter critical section here... if there's lock contention,
1240  * the resulting scheduling delays might obstruct the winmm player thread */
1241 #ifdef SYNC_CALLBACK
1242                 EnterCriticalSection(&(device->mixlock));
1243 #endif
1244                 /* retrieve current values */
1245                 fraglen = device->fraglen;
1246                 buflen = device->buflen;
1247                 pwplay = device->pwplay;
1248                 playpos = pwplay * fraglen;
1249                 mixpos = device->mixpos;
1250                 /* check remaining mixed data */
1251                 inq = DSOUND_BufPtrDiff(buflen, mixpos, playpos);
1252                 mixq = inq / fraglen;
1253                 if ((inq - (mixq * fraglen)) > 0) mixq++;
1254                 /* complete the playing buffer */
1255                 TRACE("done playing primary pos=%d\n", playpos);
1256                 pwplay++;
1257                 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1258                 /* write new values */
1259                 device->pwplay = pwplay;
1260                 device->pwqueue--;
1261                 /* queue new buffer if we have data for it */
1262                 if (inq>1) DSOUND_WaveQueue(device, inq-1);
1263 #ifdef SYNC_CALLBACK
1264                 LeaveCriticalSection(&(device->mixlock));
1265 #endif
1266         }
1267         TRACE("completed\n");
1268 }