Fixed memory leak in mixer code.
[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 LPBYTE DSOUND_tmpbuffer(IDirectSoundImpl *dsound, DWORD len)
372 {
373     TRACE("(%p,%ld)\n",dsound,len);
374
375     if (len > dsound->tmp_buffer_len) {
376         if (dsound->tmp_buffer)
377             dsound->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsound->tmp_buffer, len);
378         else
379             dsound->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
380
381         dsound->tmp_buffer_len = len;
382     }
383
384     return dsound->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         if ((buf = ibuf = DSOUND_tmpbuffer(dsb->dsound, len)) == NULL)
411                 return 0;
412
413         TRACE("MixInBuffer (%p) len = %d, dest = %ld\n", dsb, len, writepos);
414
415         ilen = DSOUND_MixerNorm(dsb, ibuf, len);
416         if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
417             (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
418             (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
419                 DSOUND_MixerVol(dsb, ibuf, len);
420
421         if (dsb->dsound->pwfx->wBitsPerSample == 8) {
422                 BYTE    *obuf = dsb->dsound->buffer + writepos;
423
424                 if ((writepos + len) <= dsb->dsound->buflen)
425                         todo = len;
426                 else
427                         todo = dsb->dsound->buflen - writepos;
428
429                 for (i = 0; i < todo; i++) {
430                         /* 8-bit WAV is unsigned */
431                         field = (*ibuf++ - 128);
432                         field += (*obuf - 128);
433                         if (field > 127) field = 127;
434                         else if (field < -128) field = -128;
435                         *obuf++ = field + 128;
436                 }
437  
438                 if (todo < len) {
439                         todo = len - todo;
440                         obuf = dsb->dsound->buffer;
441
442                         for (i = 0; i < todo; i++) {
443                                 /* 8-bit WAV is unsigned */
444                                 field = (*ibuf++ - 128);
445                                 field += (*obuf - 128);
446                                 if (field > 127) field = 127;
447                                 else if (field < -128) field = -128;
448                                 *obuf++ = field + 128;
449                         }
450                 }
451         } else {
452                 INT16   *ibufs, *obufs;
453
454                 ibufs = (INT16 *) ibuf;
455                 obufs = (INT16 *)(dsb->dsound->buffer + writepos);
456
457                 if ((writepos + len) <= dsb->dsound->buflen)
458                         todo = len / 2;
459                 else
460                         todo = (dsb->dsound->buflen - writepos) / 2;
461
462                 for (i = 0; i < todo; i++) {
463                         /* 16-bit WAV is signed */
464                         field = *ibufs++;
465                         field += *obufs;
466                         if (field > 32767) field = 32767;
467                         else if (field < -32768) field = -32768;
468                         *obufs++ = field;
469                 }
470
471                 if (todo < (len / 2)) {
472                         todo = (len / 2) - todo;
473                         obufs = (INT16 *)dsb->dsound->buffer;
474
475                         for (i = 0; i < todo; i++) {
476                                 /* 16-bit WAV is signed */
477                                 field = *ibufs++;
478                                 field += *obufs;
479                                 if (field > 32767) field = 32767;
480                                 else if (field < -32768) field = -32768;
481                                 *obufs++ = field;
482                         }
483                 }
484         }
485
486         if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
487                 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
488                  * not the MIX position... but if the sound buffer is bigger than our prebuffering
489                  * (which must be the case for the streaming buffers that need this hack anyway)
490                  * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
491                 dsb->leadin = FALSE;
492         }
493
494         dsb->buf_mixpos += ilen;
495
496         if (dsb->buf_mixpos >= dsb->buflen) {
497                 if (dsb->playflags & DSBPLAY_LOOPING) {
498                         /* wrap */
499                         dsb->buf_mixpos %= dsb->buflen;
500                         if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
501                                 dsb->leadin = FALSE; /* HACK: see above */
502                 }
503         }
504
505         return len;
506 }
507
508 static void DSOUND_PhaseCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
509 {
510         INT     ilen, field, nBlockAlign;
511         UINT    i, todo;
512         BYTE    *buf, *ibuf;
513
514         TRACE("(%p,%ld,%ld)\n",dsb,writepos,len);
515
516         nBlockAlign = dsb->dsound->pwfx->nBlockAlign;
517         len = len / nBlockAlign * nBlockAlign;  /* data alignment */
518
519         if ((buf = ibuf = DSOUND_tmpbuffer(dsb->dsound, len)) == NULL)
520                 return;
521
522         TRACE("PhaseCancel (%p) len = %ld, dest = %ld\n", dsb, len, writepos);
523
524         ilen = DSOUND_MixerNorm(dsb, ibuf, len);
525         if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
526             (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
527             (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
528                 DSOUND_MixerVol(dsb, ibuf, len);
529
530         /* subtract instead of add, to phase out premixed data */
531         if (dsb->dsound->pwfx->wBitsPerSample == 8) {
532                 BYTE    *obuf = dsb->dsound->buffer + writepos;
533
534                 if ((writepos + len) <= dsb->dsound->buflen)
535                         todo = len;
536                 else
537                         todo = dsb->dsound->buflen - writepos;
538
539                 for (i = 0; i < todo; i++) {
540                         /* 8-bit WAV is unsigned */
541                         field = (*ibuf++ - 128);
542                         field -= (*obuf - 128);
543                         if (field > 127) field = 127;
544                         else if (field < -128) field = -128;
545                         *obuf++ = field + 128;
546                 }
547  
548                 if (todo < len) {
549                         todo = len - todo;
550                         obuf = dsb->dsound->buffer;
551
552                         for (i = 0; i < todo; i++) {
553                                 /* 8-bit WAV is unsigned */
554                                 field = (*ibuf++ - 128);
555                                 field -= (*obuf - 128);
556                                 if (field > 127) field = 127;
557                                 else if (field < -128) field = -128;
558                                 *obuf++ = field + 128;
559                         }
560                 }
561         } else {
562                 INT16   *ibufs, *obufs;
563
564                 ibufs = (INT16 *) ibuf;
565                 obufs = (INT16 *)(dsb->dsound->buffer + writepos);
566
567                 if ((writepos + len) <= dsb->dsound->buflen)
568                         todo = len / 2;
569                 else
570                         todo = (dsb->dsound->buflen - writepos) / 2;
571
572                 for (i = 0; i < todo; i++) {
573                         /* 16-bit WAV is signed */
574                         field = *ibufs++;
575                         field -= *obufs;
576                         if (field > 32767) field = 32767;
577                         else if (field < -32768) field = -32768;
578                         *obufs++ = field;
579                 }
580
581                 if (todo < (len / 2)) {
582                         todo = (len / 2) - todo;
583                         obufs = (INT16 *)dsb->dsound->buffer;
584
585                         for (i = 0; i < todo; i++) {
586                                 /* 16-bit WAV is signed */
587                                 field = *ibufs++;
588                                 field -= *obufs;
589                                 if (field > 32767) field = 32767;
590                                 else if (field < -32768) field = -32768;
591                                 *obufs++ = field;
592                         }
593                 }
594         }
595 }
596
597 static void DSOUND_MixCancel(IDirectSoundBufferImpl *dsb, DWORD writepos, BOOL cancel)
598 {
599         DWORD   size, flen, len, npos, nlen;
600         INT     iAdvance = dsb->pwfx->nBlockAlign;
601         INT     oAdvance = dsb->dsound->pwfx->nBlockAlign;
602         /* determine amount of premixed data to cancel */
603         DWORD primary_done =
604                 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
605                 dsb->primary_mixpos - writepos;
606
607         TRACE("(%p, %ld), buf_mixpos=%ld\n", dsb, writepos, dsb->buf_mixpos);
608
609         /* backtrack the mix position */
610         size = primary_done / oAdvance;
611         flen = size * dsb->freqAdjust;
612         len = (flen >> DSOUND_FREQSHIFT) * iAdvance;
613         flen &= (1<<DSOUND_FREQSHIFT)-1;
614         while (dsb->freqAcc < flen) {
615                 len += iAdvance;
616                 dsb->freqAcc += 1<<DSOUND_FREQSHIFT;
617         }
618         len %= dsb->buflen;
619         npos = ((dsb->buf_mixpos < len) ? dsb->buflen : 0) +
620                 dsb->buf_mixpos - len;
621         if (dsb->leadin && (dsb->startpos > npos) && (dsb->startpos <= npos + len)) {
622                 /* stop backtracking at startpos */
623                 npos = dsb->startpos;
624                 len = ((dsb->buf_mixpos < npos) ? dsb->buflen : 0) +
625                         dsb->buf_mixpos - npos;
626                 flen = dsb->freqAcc;
627                 nlen = len / dsb->pwfx->nBlockAlign;
628                 nlen = ((nlen << DSOUND_FREQSHIFT) + flen) / dsb->freqAdjust;
629                 nlen *= dsb->dsound->pwfx->nBlockAlign;
630                 writepos =
631                         ((dsb->primary_mixpos < nlen) ? dsb->dsound->buflen : 0) +
632                         dsb->primary_mixpos - nlen;
633         }
634
635         dsb->freqAcc -= flen;
636         dsb->buf_mixpos = npos;
637         dsb->primary_mixpos = writepos;
638
639         TRACE("new buf_mixpos=%ld, primary_mixpos=%ld (len=%ld)\n",
640               dsb->buf_mixpos, dsb->primary_mixpos, len);
641
642         if (cancel) DSOUND_PhaseCancel(dsb, writepos, len);
643 }
644
645 void DSOUND_MixCancelAt(IDirectSoundBufferImpl *dsb, DWORD buf_writepos)
646 {
647 #if 0
648         DWORD   i, size, flen, len, npos, nlen;
649         INT     iAdvance = dsb->pwfx->nBlockAlign;
650         INT     oAdvance = dsb->dsound->pwfx->nBlockAlign;
651         /* determine amount of premixed data to cancel */
652         DWORD buf_done =
653                 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
654                 dsb->buf_mixpos - buf_writepos;
655 #endif
656
657         WARN("(%p, %ld), buf_mixpos=%ld\n", dsb, buf_writepos, dsb->buf_mixpos);
658         /* since this is not implemented yet, just cancel *ALL* prebuffering for now
659          * (which is faster anyway when there's only a single secondary buffer) */
660         dsb->dsound->need_remix = TRUE;
661 }
662
663 void DSOUND_ForceRemix(IDirectSoundBufferImpl *dsb)
664 {
665         TRACE("(%p)\n",dsb);
666         EnterCriticalSection(&dsb->lock);
667         if (dsb->state == STATE_PLAYING) {
668 #if 0 /* this may not be quite reliable yet */
669                 dsb->need_remix = TRUE;
670 #else
671                 dsb->dsound->need_remix = TRUE;
672 #endif
673         }
674         LeaveCriticalSection(&dsb->lock);
675 }
676
677 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
678 {
679         DWORD len, slen;
680         /* determine this buffer's write position */
681         DWORD buf_writepos = DSOUND_CalcPlayPosition(dsb, dsb->state & dsb->dsound->state, writepos,
682                                                      writepos, dsb->primary_mixpos, dsb->buf_mixpos);
683         /* determine how much already-mixed data exists */
684         DWORD buf_done =
685                 ((dsb->buf_mixpos < buf_writepos) ? dsb->buflen : 0) +
686                 dsb->buf_mixpos - buf_writepos;
687         DWORD primary_done =
688                 ((dsb->primary_mixpos < writepos) ? dsb->dsound->buflen : 0) +
689                 dsb->primary_mixpos - writepos;
690         DWORD adv_done =
691                 ((dsb->dsound->mixpos < writepos) ? dsb->dsound->buflen : 0) +
692                 dsb->dsound->mixpos - writepos;
693         DWORD played =
694                 ((buf_writepos < dsb->playpos) ? dsb->buflen : 0) +
695                 buf_writepos - dsb->playpos;
696         DWORD buf_left = dsb->buflen - buf_writepos;
697         int still_behind;
698
699         TRACE("(%p,%ld,%ld,%ld)\n",dsb,playpos,writepos,mixlen);
700         TRACE("buf_writepos=%ld, primary_writepos=%ld\n", buf_writepos, writepos);
701         TRACE("buf_done=%ld, primary_done=%ld\n", buf_done, primary_done);
702         TRACE("buf_mixpos=%ld, primary_mixpos=%ld, mixlen=%ld\n", dsb->buf_mixpos, dsb->primary_mixpos,
703               mixlen);
704         TRACE("looping=%ld, startpos=%ld, leadin=%ld\n", dsb->playflags, dsb->startpos, dsb->leadin);
705
706         /* check for notification positions */
707         if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
708             dsb->state != STATE_STARTING) {
709                 DSOUND_CheckEvent(dsb, played);
710         }
711
712         /* save write position for non-GETCURRENTPOSITION2... */
713         dsb->playpos = buf_writepos;
714
715         /* check whether CalcPlayPosition detected a mixing underrun */
716         if ((buf_done == 0) && (dsb->primary_mixpos != writepos)) {
717                 /* it did, but did we have more to play? */
718                 if ((dsb->playflags & DSBPLAY_LOOPING) ||
719                     (dsb->buf_mixpos < dsb->buflen)) {
720                         /* yes, have to recover */
721                         ERR("underrun on sound buffer %p\n", dsb);
722                         TRACE("recovering from underrun: primary_mixpos=%ld\n", writepos);
723                 }
724                 dsb->primary_mixpos = writepos;
725                 primary_done = 0;
726         }
727         /* determine how far ahead we should mix */
728         if (((dsb->playflags & DSBPLAY_LOOPING) ||
729              (dsb->leadin && (dsb->probably_valid_to != 0))) &&
730             !(dsb->dsbd.dwFlags & DSBCAPS_STATIC)) {
731                 /* if this is a streaming buffer, it typically means that
732                  * we should defer mixing past probably_valid_to as long
733                  * as we can, to avoid unnecessary remixing */
734                 /* the heavy-looking calculations shouldn't be that bad,
735                  * as any game isn't likely to be have more than 1 or 2
736                  * streaming buffers in use at any time anyway... */
737                 DWORD probably_valid_left =
738                         (dsb->probably_valid_to == (DWORD)-1) ? dsb->buflen :
739                         ((dsb->probably_valid_to < buf_writepos) ? dsb->buflen : 0) +
740                         dsb->probably_valid_to - buf_writepos;
741                 /* check for leadin condition */
742                 if ((probably_valid_left == 0) &&
743                     (dsb->probably_valid_to == dsb->startpos) &&
744                     dsb->leadin)
745                         probably_valid_left = dsb->buflen;
746                 TRACE("streaming buffer probably_valid_to=%ld, probably_valid_left=%ld\n",
747                       dsb->probably_valid_to, probably_valid_left);
748                 /* check whether the app's time is already up */
749                 if (probably_valid_left < dsb->writelead) {
750                         WARN("probably_valid_to now within writelead, possible streaming underrun\n");
751                         /* once we pass the point of no return,
752                          * no reason to hold back anymore */
753                         dsb->probably_valid_to = (DWORD)-1;
754                         /* we just have to go ahead and mix what we have,
755                          * there's no telling what the app is thinking anyway */
756                 } else {
757                         /* adjust for our frequency and our sample size */
758                         probably_valid_left = MulDiv(probably_valid_left,
759                                                      1 << DSOUND_FREQSHIFT,
760                                                      dsb->pwfx->nBlockAlign * dsb->freqAdjust) *
761                                               dsb->dsound->pwfx->nBlockAlign;
762                         /* check whether to clip mix_len */
763                         if (probably_valid_left < mixlen) {
764                                 TRACE("clipping to probably_valid_left=%ld\n", probably_valid_left);
765                                 mixlen = probably_valid_left;
766                         }
767                 }
768         }
769         /* cut mixlen with what's already been mixed */
770         if (mixlen < primary_done) {
771                 /* huh? and still CalcPlayPosition didn't
772                  * detect an underrun? */
773                 FIXME("problem with underrun detection (mixlen=%ld < primary_done=%ld)\n", mixlen, primary_done);
774                 return 0;
775         }
776         len = mixlen - primary_done;
777         TRACE("remaining mixlen=%ld\n", len);
778
779         if (len < dsb->dsound->fraglen) {
780                 /* smaller than a fragment, wait until it gets larger
781                  * before we take the mixing overhead */
782                 TRACE("mixlen not worth it, deferring mixing\n");
783                 still_behind = 1;
784                 goto post_mix;
785         }
786
787         /* ok, we know how much to mix, let's go */
788         still_behind = (adv_done > primary_done);
789         while (len) {
790                 slen = dsb->dsound->buflen - dsb->primary_mixpos;
791                 if (slen > len) slen = len;
792                 slen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, slen);
793
794                 if ((dsb->primary_mixpos < dsb->dsound->mixpos) &&
795                     (dsb->primary_mixpos + slen >= dsb->dsound->mixpos))
796                         still_behind = FALSE;
797
798                 dsb->primary_mixpos += slen; len -= slen;
799                 dsb->primary_mixpos %= dsb->dsound->buflen;
800
801                 if ((dsb->state == STATE_STOPPED) || !slen) break;
802         }
803         TRACE("new primary_mixpos=%ld, primary_advbase=%ld\n", dsb->primary_mixpos, dsb->dsound->mixpos);
804         TRACE("mixed data len=%ld, still_behind=%d\n", mixlen-len, still_behind);
805
806 post_mix:
807         /* check if buffer should be considered complete */
808         if (buf_left < dsb->writelead &&
809             !(dsb->playflags & DSBPLAY_LOOPING)) {
810                 dsb->state = STATE_STOPPED;
811                 dsb->playpos = 0;
812                 dsb->last_playpos = 0;
813                 dsb->buf_mixpos = 0;
814                 dsb->leadin = FALSE;
815                 DSOUND_CheckEvent(dsb, buf_left);
816         }
817
818         /* return how far we think the primary buffer can
819          * advance its underrun detector...*/
820         if (still_behind) return 0;
821         if ((mixlen - len) < primary_done) return 0;
822         slen = ((dsb->primary_mixpos < dsb->dsound->mixpos) ?
823                 dsb->dsound->buflen : 0) + dsb->primary_mixpos -
824                 dsb->dsound->mixpos;
825         if (slen > mixlen) {
826                 /* the primary_done and still_behind checks above should have worked */
827                 FIXME("problem with advancement calculation (advlen=%ld > mixlen=%ld)\n", slen, mixlen);
828                 slen = 0;
829         }
830         return slen;
831 }
832
833 static DWORD DSOUND_MixToPrimary(IDirectSoundImpl *dsound, DWORD playpos, DWORD writepos, DWORD mixlen, BOOL recover)
834 {
835         INT                     i, len, maxlen = 0;
836         IDirectSoundBufferImpl  *dsb;
837
838         TRACE("(%ld,%ld,%ld,%d)\n", playpos, writepos, mixlen, recover);
839         for (i = 0; i < dsound->nrofbuffers; i++) {
840                 dsb = dsound->buffers[i];
841
842                 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
843                         TRACE("Checking %p, mixlen=%ld\n", dsb, mixlen);
844                         EnterCriticalSection(&(dsb->lock));
845                         if (dsb->state == STATE_STOPPING) {
846                                 DSOUND_MixCancel(dsb, writepos, TRUE);
847                                 dsb->state = STATE_STOPPED;
848                                 DSOUND_CheckEvent(dsb, 0);
849                         } else {
850                                 if ((dsb->state == STATE_STARTING) || recover) {
851                                         dsb->primary_mixpos = writepos;
852                                         dsb->cvolpan = dsb->volpan;
853                                         dsb->need_remix = FALSE;
854                                 }
855                                 else if (dsb->need_remix) {
856                                         DSOUND_MixCancel(dsb, writepos, TRUE);
857                                         dsb->cvolpan = dsb->volpan;
858                                         dsb->need_remix = FALSE;
859                                 }
860                                 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
861                                 if (dsb->state == STATE_STARTING)
862                                         dsb->state = STATE_PLAYING;
863                                 maxlen = (len > maxlen) ? len : maxlen;
864                         }
865                         LeaveCriticalSection(&(dsb->lock));
866                 }
867         }
868
869         return maxlen;
870 }
871
872 static void DSOUND_MixReset(IDirectSoundImpl *dsound, DWORD writepos)
873 {
874         INT                     i;
875         IDirectSoundBufferImpl  *dsb;
876         int nfiller;
877
878         TRACE("(%ld)\n", writepos);
879
880         /* the sound of silence */
881         nfiller = dsound->pwfx->wBitsPerSample == 8 ? 128 : 0;
882
883         /* reset all buffer mix positions */
884         for (i = 0; i < dsound->nrofbuffers; i++) {
885                 dsb = dsound->buffers[i];
886
887                 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
888                         TRACE("Resetting %p\n", dsb);
889                         EnterCriticalSection(&(dsb->lock));
890                         if (dsb->state == STATE_STOPPING) {
891                                 dsb->state = STATE_STOPPED;
892                         }
893                         else if (dsb->state == STATE_STARTING) {
894                                 /* nothing */
895                         } else {
896                                 DSOUND_MixCancel(dsb, writepos, FALSE);
897                                 dsb->cvolpan = dsb->volpan;
898                                 dsb->need_remix = FALSE;
899                         }
900                         LeaveCriticalSection(&(dsb->lock));
901                 }
902         }
903
904         /* wipe out premixed data */
905         if (dsound->mixpos < writepos) {
906                 memset(dsound->buffer + writepos, nfiller, dsound->buflen - writepos);
907                 memset(dsound->buffer, nfiller, dsound->mixpos);
908         } else {
909                 memset(dsound->buffer + writepos, nfiller, dsound->mixpos - writepos);
910         }
911
912         /* reset primary mix position */
913         dsound->mixpos = writepos;
914 }
915
916 static void DSOUND_CheckReset(IDirectSoundImpl *dsound, DWORD writepos)
917 {
918         TRACE("(%p,%ld)\n",dsound,writepos);
919         if (dsound->need_remix) {
920                 DSOUND_MixReset(dsound, writepos);
921                 dsound->need_remix = FALSE;
922                 /* maximize Half-Life performance */
923                 dsound->prebuf = ds_snd_queue_min;
924                 dsound->precount = 0;
925         } else {
926                 dsound->precount++;
927                 if (dsound->precount >= 4) {
928                         if (dsound->prebuf < ds_snd_queue_max)
929                                 dsound->prebuf++;
930                         dsound->precount = 0;
931                 }
932         }
933         TRACE("premix adjust: %d\n", dsound->prebuf);
934 }
935
936 void DSOUND_WaveQueue(IDirectSoundImpl *dsound, DWORD mixq)
937 {
938         TRACE("(%p,%ld)\n",dsound,mixq);
939         if (mixq + dsound->pwqueue > ds_hel_queue) mixq = ds_hel_queue - dsound->pwqueue;
940         TRACE("queueing %ld buffers, starting at %d\n", mixq, dsound->pwwrite);
941         for (; mixq; mixq--) {
942                 waveOutWrite(dsound->hwo, dsound->pwave[dsound->pwwrite], sizeof(WAVEHDR));
943                 dsound->pwwrite++;
944                 if (dsound->pwwrite >= DS_HEL_FRAGS) dsound->pwwrite = 0;
945                 dsound->pwqueue++;
946         }
947 }
948
949 /* #define SYNC_CALLBACK */
950
951 void DSOUND_PerformMix(IDirectSoundImpl *dsound)
952 {
953         int nfiller;
954         BOOL forced;
955         HRESULT hres;
956
957         TRACE("(%p)\n", dsound);
958
959         /* the sound of silence */
960         nfiller = dsound->pwfx->wBitsPerSample == 8 ? 128 : 0;
961
962         /* whether the primary is forced to play even without secondary buffers */
963         forced = ((dsound->state == STATE_PLAYING) || (dsound->state == STATE_STARTING));
964
965         if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
966                 BOOL paused = ((dsound->state == STATE_STOPPED) || (dsound->state == STATE_STARTING));
967                 /* FIXME: document variables */
968                 DWORD playpos, writepos, inq, maxq, frag;
969                 if (dsound->hwbuf) {
970                         hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, &writepos);
971                         if (hres) {
972                             WARN("IDsDriverBuffer_GetPosition failed\n");
973                             return;
974                         }
975                         /* Well, we *could* do Just-In-Time mixing using the writepos,
976                          * but that's a little bit ambitious and unnecessary... */
977                         /* rather add our safety margin to the writepos, if we're playing */
978                         if (!paused) {
979                                 writepos += dsound->writelead;
980                                 writepos %= dsound->buflen;
981                         } else writepos = playpos;
982                 } else {
983                         playpos = dsound->pwplay * dsound->fraglen;
984                         writepos = playpos;
985                         if (!paused) {
986                                 writepos += ds_hel_margin * dsound->fraglen;
987                                 writepos %= dsound->buflen;
988                         }
989                 }
990                 TRACE("primary playpos=%ld, writepos=%ld, clrpos=%ld, mixpos=%ld, buflen=%ld\n",
991                       playpos,writepos,dsound->playpos,dsound->mixpos,dsound->buflen);
992                 assert(dsound->playpos < dsound->buflen);
993                 /* wipe out just-played sound data */
994                 if (playpos < dsound->playpos) {
995                         memset(dsound->buffer + dsound->playpos, nfiller, dsound->buflen - dsound->playpos);
996                         memset(dsound->buffer, nfiller, playpos);
997                 } else {
998                         memset(dsound->buffer + dsound->playpos, nfiller, playpos - dsound->playpos);
999                 }
1000                 dsound->playpos = playpos;
1001
1002                 EnterCriticalSection(&(dsound->mixlock));
1003
1004                 /* reset mixing if necessary */
1005                 DSOUND_CheckReset(dsound, writepos);
1006
1007                 /* check how much prebuffering is left */
1008                 inq = dsound->mixpos;
1009                 if (inq < writepos)
1010                         inq += dsound->buflen;
1011                 inq -= writepos;
1012
1013                 /* find the maximum we can prebuffer */
1014                 if (!paused) {
1015                         maxq = playpos;
1016                         if (maxq < writepos)
1017                                 maxq += dsound->buflen;
1018                         maxq -= writepos;
1019                 } else maxq = dsound->buflen;
1020
1021                 /* clip maxq to dsound->prebuf */
1022                 frag = dsound->prebuf * dsound->fraglen;
1023                 if (maxq > frag) maxq = frag;
1024
1025                 /* check for consistency */
1026                 if (inq > maxq) {
1027                         /* the playback position must have passed our last
1028                          * mixed position, i.e. it's an underrun, or we have
1029                          * nothing more to play */
1030                         TRACE("reached end of mixed data (inq=%ld, maxq=%ld)\n", inq, maxq);
1031                         inq = 0;
1032                         /* stop the playback now, to allow buffers to refill */
1033                         if (dsound->state == STATE_PLAYING) {
1034                                 dsound->state = STATE_STARTING;
1035                         }
1036                         else if (dsound->state == STATE_STOPPING) {
1037                                 dsound->state = STATE_STOPPED;
1038                         }
1039                         else {
1040                                 /* how can we have an underrun if we aren't playing? */
1041                                 WARN("unexpected primary state (%ld)\n", dsound->state);
1042                         }
1043 #ifdef SYNC_CALLBACK
1044                         /* DSOUND_callback may need this lock */
1045                         LeaveCriticalSection(&(dsound->mixlock));
1046 #endif
1047                         if (DSOUND_PrimaryStop(dsound) != DS_OK)
1048                                 WARN("DSOUND_PrimaryStop failed\n");
1049 #ifdef SYNC_CALLBACK
1050                         EnterCriticalSection(&(dsound->mixlock));
1051 #endif
1052                         if (dsound->hwbuf) {
1053                                 /* the Stop is supposed to reset play position to beginning of buffer */
1054                                 /* unfortunately, OSS is not able to do so, so get current pointer */
1055                                 hres = IDsDriverBuffer_GetPosition(dsound->hwbuf, &playpos, NULL);
1056                                 if (hres) {
1057                                         LeaveCriticalSection(&(dsound->mixlock));
1058                                         WARN("IDsDriverBuffer_GetPosition failed\n");
1059                                         return;
1060                                 }
1061                         } else {
1062                                 playpos = dsound->pwplay * dsound->fraglen;
1063                         }
1064                         writepos = playpos;
1065                         dsound->playpos = playpos;
1066                         dsound->mixpos = writepos;
1067                         inq = 0;
1068                         maxq = dsound->buflen;
1069                         if (maxq > frag) maxq = frag;
1070                         memset(dsound->buffer, nfiller, dsound->buflen);
1071                         paused = TRUE;
1072                 }
1073
1074                 /* do the mixing */
1075                 frag = DSOUND_MixToPrimary(dsound, playpos, writepos, maxq, paused);
1076                 if (forced) frag = maxq - inq;
1077                 dsound->mixpos += frag;
1078                 dsound->mixpos %= dsound->buflen;
1079
1080                 if (frag) {
1081                         /* buffers have been filled, restart playback */
1082                         if (dsound->state == STATE_STARTING) {
1083                                 dsound->state = STATE_PLAYING;
1084                         }
1085                         else if (dsound->state == STATE_STOPPED) {
1086                                 /* the dsound is supposed to play if there's something to play
1087                                  * even if it is reported as stopped, so don't let this confuse you */
1088                                 dsound->state = STATE_STOPPING;
1089                         }
1090                         LeaveCriticalSection(&(dsound->mixlock));
1091                         if (paused) {
1092                                 if (DSOUND_PrimaryPlay(dsound) != DS_OK)
1093                                         WARN("DSOUND_PrimaryPlay failed\n");
1094                                 else
1095                                         TRACE("starting playback\n");
1096                         }
1097                 }
1098                 else
1099                         LeaveCriticalSection(&(dsound->mixlock));
1100         } else {
1101                 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
1102                 if (dsound->state == STATE_STARTING) {
1103                         if (DSOUND_PrimaryPlay(dsound) != DS_OK)
1104                                 WARN("DSOUND_PrimaryPlay failed\n");
1105                         else
1106                                 dsound->state = STATE_PLAYING;
1107                 }
1108                 else if (dsound->state == STATE_STOPPING) {
1109                         if (DSOUND_PrimaryStop(dsound) != DS_OK)
1110                                 WARN("DSOUND_PrimaryStop failed\n");
1111                         else
1112                                 dsound->state = STATE_STOPPED;
1113                 }
1114         }
1115 }
1116
1117 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1118 {
1119         IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1120         DWORD start_time =  GetTickCount();
1121         DWORD end_time;
1122         TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
1123         TRACE("entering at %ld\n", start_time);
1124
1125         if (dsound != This) {
1126                 ERR("dsound died without killing us?\n");
1127                 timeKillEvent(timerID);
1128                 timeEndPeriod(DS_TIME_RES);
1129                 return;
1130         }
1131
1132         RtlAcquireResourceShared(&(This->buffer_list_lock), TRUE);
1133
1134         if (This->ref)
1135                 DSOUND_PerformMix(This);
1136
1137         RtlReleaseResource(&(This->buffer_list_lock));
1138
1139         end_time = GetTickCount();
1140         TRACE("completed processing at %ld, duration = %ld\n", end_time, end_time - start_time);
1141 }
1142
1143 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1144 {
1145         IDirectSoundImpl* This = (IDirectSoundImpl*)dwUser;
1146         TRACE("(%p,%x,%lx,%lx,%lx)\n",hwo,msg,dwUser,dw1,dw2);
1147         TRACE("entering at %ld, msg=%08x(%s)\n", GetTickCount(), msg, 
1148                 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" : 
1149                 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1150         if (msg == MM_WOM_DONE) {
1151                 DWORD inq, mixq, fraglen, buflen, pwplay, playpos, mixpos;
1152                 if (This->pwqueue == (DWORD)-1) {
1153                         TRACE("completed due to reset\n");
1154                         return;
1155                 }
1156 /* it could be a bad idea to enter critical section here... if there's lock contention,
1157  * the resulting scheduling delays might obstruct the winmm player thread */
1158 #ifdef SYNC_CALLBACK
1159                 EnterCriticalSection(&(This->mixlock));
1160 #endif
1161                 /* retrieve current values */
1162                 fraglen = This->fraglen;
1163                 buflen = This->buflen;
1164                 pwplay = This->pwplay;
1165                 playpos = pwplay * fraglen;
1166                 mixpos = This->mixpos;
1167                 /* check remaining mixed data */
1168                 inq = ((mixpos < playpos) ? buflen : 0) + mixpos - playpos;
1169                 mixq = inq / fraglen;
1170                 if ((inq - (mixq * fraglen)) > 0) mixq++;
1171                 /* complete the playing buffer */
1172                 TRACE("done playing primary pos=%ld\n", playpos);
1173                 pwplay++;
1174                 if (pwplay >= DS_HEL_FRAGS) pwplay = 0;
1175                 /* write new values */
1176                 This->pwplay = pwplay;
1177                 This->pwqueue--;
1178                 /* queue new buffer if we have data for it */
1179                 if (inq>1) DSOUND_WaveQueue(This, inq-1);
1180 #ifdef SYNC_CALLBACK
1181                 LeaveCriticalSection(&(This->mixlock));
1182 #endif
1183         }
1184         TRACE("completed\n");
1185 }