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