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