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