rpcrt4: Try a lot harder to resuse existing connections by comparing inside the RpcQu...
[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  * Copyright 2007 Peter Dons Tychsen
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include <assert.h>
24 #include <stdarg.h>
25 #include <math.h>       /* Insomnia - pow() function */
26
27 #define NONAMELESSSTRUCT
28 #define NONAMELESSUNION
29 #include "windef.h"
30 #include "winbase.h"
31 #include "winuser.h"
32 #include "mmsystem.h"
33 #include "winternl.h"
34 #include "wine/debug.h"
35 #include "dsound.h"
36 #include "dsdriver.h"
37 #include "dsound_private.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
40
41 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
42 {
43         double temp;
44         TRACE("(%p)\n",volpan);
45
46         TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
47         /* the AmpFactors are expressed in 16.16 fixed point */
48         volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
49         /* FIXME: dwPan{Left|Right}AmpFactor */
50
51         /* FIXME: use calculated vol and pan ampfactors */
52         temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
53         volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
54         temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
55         volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
56
57         TRACE("left = %x, right = %x\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
58 }
59
60 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
61 {
62     double left,right;
63     TRACE("(%p)\n",volpan);
64
65     TRACE("left=%x, right=%x\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
66     if (volpan->dwTotalLeftAmpFactor==0)
67         left=-10000;
68     else
69         left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
70     if (volpan->dwTotalRightAmpFactor==0)
71         right=-10000;
72     else
73         right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
74     if (left<right)
75     {
76         volpan->lVolume=right;
77         volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
78     }
79     else
80     {
81         volpan->lVolume=left;
82         volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
83     }
84     if (volpan->lVolume < -10000)
85         volpan->lVolume=-10000;
86     volpan->lPan=right-left;
87     if (volpan->lPan < -10000)
88         volpan->lPan=-10000;
89
90     TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
91 }
92
93 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
94 {
95         TRACE("(%p)\n",dsb);
96
97         /* calculate the 10ms write lead */
98         dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
99 }
100
101 /**
102  * Check for application callback requests for when the play position
103  * reaches certain points.
104  *
105  * The offsets that will be triggered will be those between the recorded
106  * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
107  * beyond that position.
108  */
109 void DSOUND_CheckEvent(IDirectSoundBufferImpl *dsb, int len)
110 {
111         int                     i;
112         DWORD                   offset;
113         LPDSBPOSITIONNOTIFY     event;
114         TRACE("(%p,%d)\n",dsb,len);
115
116         if (dsb->nrofnotifies == 0)
117                 return;
118
119         TRACE("(%p) buflen = %d, playpos = %d, len = %d\n",
120                 dsb, dsb->buflen, dsb->playpos, len);
121         for (i = 0; i < dsb->nrofnotifies ; i++) {
122                 event = dsb->notifies + i;
123                 offset = event->dwOffset;
124                 TRACE("checking %d, position %d, event = %p\n",
125                         i, offset, event->hEventNotify);
126                 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
127                 /* OK. [Inside DirectX, p274] */
128                 /*  */
129                 /* This also means we can't sort the entries by offset, */
130                 /* because DSBPN_OFFSETSTOP == -1 */
131                 if (offset == DSBPN_OFFSETSTOP) {
132                         if (dsb->state == STATE_STOPPED) {
133                                 SetEvent(event->hEventNotify);
134                                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
135                                 return;
136                         } else
137                                 return;
138                 }
139                 if ((dsb->playpos + len) >= dsb->buflen) {
140                         if ((offset < ((dsb->playpos + len) % dsb->buflen)) ||
141                             (offset >= dsb->playpos)) {
142                                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
143                                 SetEvent(event->hEventNotify);
144                         }
145                 } else {
146                         if ((offset >= dsb->playpos) && (offset < (dsb->playpos + len))) {
147                                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
148                                 SetEvent(event->hEventNotify);
149                         }
150                 }
151         }
152 }
153
154 /* WAV format info can be found at:
155  *
156  *    http://www.cwi.nl/ftp/audio/AudioFormats.part2
157  *    ftp://ftp.cwi.nl/pub/audio/RIFF-format
158  *
159  * Import points to remember:
160  *    8-bit WAV is unsigned
161  *    16-bit WAV is signed
162  */
163  /* Use the same formulas as pcmconverter.c */
164 static inline INT16 cvtU8toS16(BYTE b)
165 {
166     return (short)((b+(b << 8))-32768);
167 }
168
169 static inline BYTE cvtS16toU8(INT16 s)
170 {
171     return (s >> 8) ^ (unsigned char)0x80;
172 }
173
174 /**
175  * Copy a single frame from the given input buffer to the given output buffer.
176  * Translate 8 <-> 16 bits and mono <-> stereo
177  */
178 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, const BYTE *ibuf, BYTE *obuf )
179 {
180         DirectSoundDevice * device = dsb->device;
181         INT fl,fr;
182
183         if (dsb->pwfx->wBitsPerSample == 8)  {
184                 if (device->pwfx->wBitsPerSample == 8 &&
185                     device->pwfx->nChannels == dsb->pwfx->nChannels) {
186                         /* avoid needless 8->16->8 conversion */
187                         *obuf=*ibuf;
188                         if (dsb->pwfx->nChannels==2)
189                                 *(obuf+1)=*(ibuf+1);
190                         return;
191                 }
192                 fl = cvtU8toS16(*ibuf);
193                 fr = (dsb->pwfx->nChannels==2 ? cvtU8toS16(*(ibuf + 1)) : fl);
194         } else {
195                 fl = *((const INT16 *)ibuf);
196                 fr = (dsb->pwfx->nChannels==2 ? *(((const INT16 *)ibuf) + 1)  : fl);
197         }
198
199         if (device->pwfx->nChannels == 2) {
200                 if (device->pwfx->wBitsPerSample == 8) {
201                         *obuf = cvtS16toU8(fl);
202                         *(obuf + 1) = cvtS16toU8(fr);
203                         return;
204                 }
205                 if (device->pwfx->wBitsPerSample == 16) {
206                         *((INT16 *)obuf) = fl;
207                         *(((INT16 *)obuf) + 1) = fr;
208                         return;
209                 }
210         }
211         if (device->pwfx->nChannels == 1) {
212                 fl = (fl + fr) >> 1;
213                 if (device->pwfx->wBitsPerSample == 8) {
214                         *obuf = cvtS16toU8(fl);
215                         return;
216                 }
217                 if (device->pwfx->wBitsPerSample == 16) {
218                         *((INT16 *)obuf) = fl;
219                         return;
220                 }
221         }
222 }
223
224 /**
225  * Mix at most the given amount of data into the given device buffer from the
226  * given secondary buffer, starting from the dsb's first currently unmixed
227  * frame (buf_mixpos), translating frequency (pitch), stereo/mono and
228  * bits-per-sample. The secondary buffer sample is looped if it is not
229  * long enough and it is a looping buffer.
230  * (Doesn't perform any mixing - this is a straight copy operation).
231  *
232  * Now with PerfectPitch (tm) technology
233  *
234  * dsb = the secondary buffer
235  * buf = the device buffer
236  * len = number of bytes to store in the device buffer
237  *
238  * Returns: the number of bytes read from the secondary buffer
239  *   (ie. len, adjusted for frequency, number of channels and sample size,
240  *    and limited by buffer length for non-looping buffers)
241  */
242 static INT DSOUND_MixerNorm(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
243 {
244         INT     i, size, ipos, ilen;
245         BYTE    *ibp, *obp;
246         INT     iAdvance = dsb->pwfx->nBlockAlign;
247         INT     oAdvance = dsb->device->pwfx->nBlockAlign;
248
249         ibp = dsb->buffer->memory + dsb->buf_mixpos;
250         obp = buf;
251
252         TRACE("(%p, %p, %p), buf_mixpos=%d\n", dsb, ibp, obp, dsb->buf_mixpos);
253         /* Check for the best case */
254         if ((dsb->freq == dsb->device->pwfx->nSamplesPerSec) &&
255             (dsb->pwfx->wBitsPerSample == dsb->device->pwfx->wBitsPerSample) &&
256             (dsb->pwfx->nChannels == dsb->device->pwfx->nChannels)) {
257                 INT bytesleft = dsb->buflen - dsb->buf_mixpos;
258                 TRACE("(%p) Best case\n", dsb);
259                 if (len <= bytesleft )
260                         CopyMemory(obp, ibp, len);
261                 else { /* wrap */
262                         CopyMemory(obp, ibp, bytesleft);
263                         CopyMemory(obp + bytesleft, dsb->buffer->memory, len - bytesleft);
264                 }
265                 return len;
266         }
267
268         /* Check for same sample rate */
269         if (dsb->freq == dsb->device->pwfx->nSamplesPerSec) {
270                 TRACE("(%p) Same sample rate %d = primary %d\n", dsb,
271                         dsb->freq, dsb->device->pwfx->nSamplesPerSec);
272                 ilen = 0;
273                 for (i = 0; i < len; i += oAdvance) {
274                         cp_fields(dsb, ibp, obp );
275                         ibp += iAdvance;
276                         ilen += iAdvance;
277                         obp += oAdvance;
278                         if (ibp >= (BYTE *)(dsb->buffer->memory + dsb->buflen))
279                                 ibp = dsb->buffer->memory;      /* wrap */
280                 }
281                 return (ilen);
282         }
283
284         /* Mix in different sample rates */
285         /* */
286         /* New PerfectPitch(tm) Technology (c) 1998 Rob Riggs */
287         /* Patent Pending :-] */
288
289         /* Patent enhancements (c) 2000 Ove KÃ¥ven,
290          * TransGaming Technologies Inc. */
291
292         /* FIXME("(%p) Adjusting frequency: %ld -> %ld (need optimization)\n",
293            dsb, dsb->freq, dsb->device->pwfx->nSamplesPerSec); */
294
295         size = len / oAdvance;
296         ilen = 0;
297         ipos = dsb->buf_mixpos;
298         for (i = 0; i < size; i++) {
299                 cp_fields(dsb, (dsb->buffer->memory + ipos), obp);
300                 obp += oAdvance;
301                 dsb->freqAcc += dsb->freqAdjust;
302                 if (dsb->freqAcc >= (1<<DSOUND_FREQSHIFT)) {
303                         ULONG adv = (dsb->freqAcc>>DSOUND_FREQSHIFT) * iAdvance;
304                         dsb->freqAcc &= (1<<DSOUND_FREQSHIFT)-1;
305                         ipos += adv; ilen += adv;
306                         ipos %= dsb->buflen;
307                 }
308         }
309         return ilen;
310 }
311
312 static void DSOUND_MixerVol(IDirectSoundBufferImpl *dsb, BYTE *buf, INT len)
313 {
314         INT     i;
315         BYTE    *bpc = buf;
316         INT16   *bps = (INT16 *) buf;
317
318         TRACE("(%p,%p,%d)\n",dsb,buf,len);
319         TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalLeftAmpFactor,
320                 dsb->volpan.dwTotalRightAmpFactor);
321
322         if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
323             (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
324             !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
325                 return;         /* Nothing to do */
326
327         /* If we end up with some bozo coder using panning or 3D sound */
328         /* with a mono primary buffer, it could sound very weird using */
329         /* this method. Oh well, tough patooties. */
330
331         switch (dsb->device->pwfx->wBitsPerSample) {
332         case 8:
333                 /* 8-bit WAV is unsigned, but we need to operate */
334                 /* on signed data for this to work properly */
335                 switch (dsb->device->pwfx->nChannels) {
336                 case 1:
337                         for (i = 0; i < len; i++) {
338                                 INT val = *bpc - 128;
339                                 val = (val * dsb->volpan.dwTotalLeftAmpFactor) >> 16;
340                                 *bpc = val + 128;
341                                 bpc++;
342                         }
343                         break;
344                 case 2:
345                         for (i = 0; i < len; i+=2) {
346                                 INT val = *bpc - 128;
347                                 val = (val * dsb->volpan.dwTotalLeftAmpFactor) >> 16;
348                                 *bpc++ = val + 128;
349                                 val = *bpc - 128;
350                                 val = (val * dsb->volpan.dwTotalRightAmpFactor) >> 16;
351                                 *bpc = val + 128;
352                                 bpc++;
353                         }
354                         break;
355                 default:
356                         FIXME("doesn't support %d channels\n", dsb->device->pwfx->nChannels);
357                         break;
358                 }
359                 break;
360         case 16:
361                 /* 16-bit WAV is signed -- much better */
362                 switch (dsb->device->pwfx->nChannels) {
363                 case 1:
364                         for (i = 0; i < len; i += 2) {
365                                 *bps = (*bps * dsb->volpan.dwTotalLeftAmpFactor) >> 16;
366                                 bps++;
367                         }
368                         break;
369                 case 2:
370                         for (i = 0; i < len; i += 4) {
371                                 *bps = (*bps * dsb->volpan.dwTotalLeftAmpFactor) >> 16;
372                                 bps++;
373                                 *bps = (*bps * dsb->volpan.dwTotalRightAmpFactor) >> 16;
374                                 bps++;
375                         }
376                         break;
377                 default:
378                         FIXME("doesn't support %d channels\n", dsb->device->pwfx->nChannels);
379                         break;
380                 }
381                 break;
382         default:
383                 FIXME("doesn't support %d bit samples\n", dsb->device->pwfx->wBitsPerSample);
384                 break;
385         }
386 }
387
388 /**
389  * Make sure the device's tmp_buffer is at least the given size. Return a
390  * pointer to it.
391  */
392 static LPBYTE DSOUND_tmpbuffer(DirectSoundDevice *device, DWORD len)
393 {
394     TRACE("(%p,%d)\n", device, len);
395
396     if (len > device->tmp_buffer_len) {
397         if (device->tmp_buffer)
398             device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, device->tmp_buffer, len);
399         else
400             device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
401
402         device->tmp_buffer_len = len;
403     }
404
405     return device->tmp_buffer;
406 }
407
408 /**
409  * Mix (at most) the given number of bytes into the given position of the
410  * device buffer, from the secondary buffer "dsb" (starting at the current
411  * mix position for that buffer).
412  *
413  * Returns the number of bytes actually mixed into the device buffer. This
414  * will match fraglen unless the end of the secondary buffer is reached
415  * (and it is not looping).
416  *
417  * dsb  = the secondary buffer to mix from
418  * writepos = position (offset) in device buffer to write at
419  * fraglen = number of bytes to mix
420  */
421 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
422 {
423         INT     i, len, ilen, field, todo;
424         BYTE    *buf, *ibuf;
425
426         TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
427
428         len = fraglen;
429         if (!(dsb->playflags & DSBPLAY_LOOPING)) {
430                 /* This buffer is not looping, so make sure the requested
431                  * length will not take us past the end of the buffer */
432                 int secondary_remainder = dsb->buflen - dsb->buf_mixpos;
433                 int adjusted_remainder = MulDiv(dsb->device->pwfx->nAvgBytesPerSec, secondary_remainder, dsb->nAvgBytesPerSec);
434                 assert(adjusted_remainder >= 0);
435                         /* The adjusted remainder must be at least one sample,
436                          * otherwise we will never reach the end of the
437                          * secondary buffer, as there will perpetually be a
438                          * fractional remainder */
439                 TRACE("secondary_remainder = %d, adjusted_remainder = %d, len = %d\n", secondary_remainder, adjusted_remainder, len);
440                 if (adjusted_remainder < len) {
441                         TRACE("clipping len to remainder of secondary buffer\n");
442                         len = adjusted_remainder;
443                 }
444                 if (len == 0)
445                         return 0;
446         }
447
448         if (len % dsb->device->pwfx->nBlockAlign) {
449                 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
450                 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
451                 len -= len % nBlockAlign; /* data alignment */
452         }
453
454         /* Create temp buffer to hold actual resulting data */
455         if ((buf = ibuf = DSOUND_tmpbuffer(dsb->device, len)) == NULL)
456                 return 0;
457
458         TRACE("MixInBuffer (%p) len = %d, dest = %d\n", dsb, len, writepos);
459
460         /* first, copy the data from the DirectSoundBuffer into the temporary
461            buffer, translating frequency/bits-per-sample/number-of-channels
462            to match the device settings */
463         ilen = DSOUND_MixerNorm(dsb, ibuf, len);
464
465         /* then apply the correct volume, if necessary */
466         if ((dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) ||
467             (dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) ||
468             (dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
469                 DSOUND_MixerVol(dsb, ibuf, len);
470
471         /* Now mix the temporary buffer into the devices main buffer */
472         if (dsb->device->pwfx->wBitsPerSample == 8) {
473                 BYTE    *obuf = dsb->device->buffer + writepos;
474
475                 if ((writepos + len) <= dsb->device->buflen)
476                         todo = len;
477                 else
478                         todo = dsb->device->buflen - writepos;
479
480                 for (i = 0; i < todo; i++) {
481                         /* 8-bit WAV is unsigned */
482                         field = (*ibuf++ - 128);
483                         field += (*obuf - 128);
484                         if (field > 127) field = 127;
485                         else if (field < -128) field = -128;
486                         *obuf++ = field + 128;
487                 }
488  
489                 if (todo < len) {
490                         todo = len - todo;
491                         obuf = dsb->device->buffer;
492
493                         for (i = 0; i < todo; i++) {
494                                 /* 8-bit WAV is unsigned */
495                                 field = (*ibuf++ - 128);
496                                 field += (*obuf - 128);
497                                 if (field > 127) field = 127;
498                                 else if (field < -128) field = -128;
499                                 *obuf++ = field + 128;
500                         }
501                 }
502         } else {
503                 INT16   *ibufs, *obufs;
504
505                 ibufs = (INT16 *) ibuf;
506                 obufs = (INT16 *)(dsb->device->buffer + writepos);
507
508                 if ((writepos + len) <= dsb->device->buflen)
509                         todo = len / 2;
510                 else
511                         todo = (dsb->device->buflen - writepos) / 2;
512
513                 for (i = 0; i < todo; i++) {
514                         /* 16-bit WAV is signed */
515                         field = *ibufs++;
516                         field += *obufs;
517                         if (field > 32767) field = 32767;
518                         else if (field < -32768) field = -32768;
519                         *obufs++ = field;
520                 }
521
522                 if (todo < (len / 2)) {
523                         todo = (len / 2) - todo;
524                         obufs = (INT16 *)dsb->device->buffer;
525
526                         for (i = 0; i < todo; i++) {
527                                 /* 16-bit WAV is signed */
528                                 field = *ibufs++;
529                                 field += *obufs;
530                                 if (field > 32767) field = 32767;
531                                 else if (field < -32768) field = -32768;
532                                 *obufs++ = field;
533                         }
534                 }
535         }
536
537         if (dsb->leadin && (dsb->startpos > dsb->buf_mixpos) && (dsb->startpos <= dsb->buf_mixpos + ilen)) {
538                 /* HACK... leadin should be reset when the PLAY position reaches the startpos,
539                  * not the MIX position... but if the sound buffer is bigger than our prebuffering
540                  * (which must be the case for the streaming buffers that need this hack anyway)
541                  * plus DS_HEL_MARGIN or equivalent, then this ought to work anyway. */
542                 dsb->leadin = FALSE;
543         }
544
545         dsb->buf_mixpos += ilen;
546
547         if (dsb->buf_mixpos >= dsb->buflen) {
548                 if (dsb->playflags & DSBPLAY_LOOPING) {
549                         /* wrap */
550                         dsb->buf_mixpos %= dsb->buflen;
551                         if (dsb->leadin && (dsb->startpos <= dsb->buf_mixpos))
552                                 dsb->leadin = FALSE; /* HACK: see above */
553                 } else if (dsb->buf_mixpos > dsb->buflen) {
554                         ERR("Mixpos (%u) past buflen (%u), capping...\n", dsb->buf_mixpos, dsb->buflen);
555                         dsb->buf_mixpos = dsb->buflen;
556                 }
557         }
558
559         return len;
560 }
561
562 /**
563  * Calculate the distance between two buffer offsets, taking wraparound
564  * into account.
565  */
566 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
567 {
568         if (ptr1 >= ptr2) {
569                 return ptr1 - ptr2;
570         } else {
571                 return buflen + ptr1 - ptr2;
572         }
573 }
574
575 /**
576  * Mix some frames from the given secondary buffer "dsb" into the device
577  * primary buffer.
578  *
579  * dsb = the secondary buffer
580  * playpos = the current play position in the device buffer (primary buffer)
581  * writepos = the current safe-to-write position in the device buffer
582  * mixlen = the maximum number of bytes in the primary buffer to mix, from the
583  *          current writepos.
584  *
585  * Returns: the number of bytes beyond the writepos that were mixed.
586  */
587 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD playpos, DWORD writepos, DWORD mixlen)
588 {
589         /* The buffer's primary_mixpos may be before or after the the device
590          * buffer's mixpos, but both must be ahead of writepos. */
591         DWORD primary_done;
592
593         TRACE("(%p,%d,%d,%d)\n",dsb,playpos,writepos,mixlen);
594         TRACE("writepos=%d, buf_mixpos=%d, primary_mixpos=%d, mixlen=%d\n", writepos, dsb->buf_mixpos, dsb->primary_mixpos, mixlen);
595         TRACE("looping=%d, startpos=%d, leadin=%d, buflen=%d\n", dsb->playflags, dsb->startpos, dsb->leadin, dsb->buflen);
596
597         /* check for notification positions */
598         if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
599             dsb->state != STATE_STARTING) {
600                 DSOUND_CheckEvent(dsb, mixlen);
601         }
602
603         /* save write position for non-GETCURRENTPOSITION2... */
604         dsb->playpos = writepos;
605
606         /* calculate how much pre-buffering has already been done for this buffer */
607         primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
608
609         /* sanity */
610         if(mixlen < primary_done)
611         {
612                 /* Should *NEVER* happen */
613                 ERR("Fatal error. Under/Overflow? primary_done=%d, mixpos=%d, primary_mixpos=%d, writepos=%d, playpos=%d\n", primary_done,dsb->buf_mixpos,dsb->primary_mixpos, writepos, playpos);
614                 return 0;
615         }
616
617         /* take into acount already mixed data */
618         mixlen = mixlen - primary_done;
619
620         TRACE("mixlen (primary) = %i\n", mixlen);
621
622         /* clip to valid length */
623         mixlen = (dsb->buflen < mixlen) ? dsb->buflen : mixlen;
624
625         TRACE("primary_done=%d, mixlen (buffer)=%d\n", primary_done, mixlen);
626
627         /* mix more data */
628         mixlen = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixlen);
629
630         /* increase mix position */
631         dsb->primary_mixpos += mixlen;
632         dsb->primary_mixpos %= dsb->device->buflen;
633
634         TRACE("new primary_mixpos=%d, mixed data len=%d, buffer left = %d\n",
635                 dsb->primary_mixpos, mixlen, (dsb->buflen - dsb->buf_mixpos));
636
637         /* re-calculate the primary done */
638         primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
639
640         /* check if buffer should be considered complete */
641         if (((dsb->buflen - dsb->buf_mixpos) < dsb->writelead) &&
642             !(dsb->playflags & DSBPLAY_LOOPING)) {
643
644                 TRACE("Buffer reached end. Stopped\n");
645
646                 dsb->state = STATE_STOPPED;
647                 dsb->playpos = 0;
648                 dsb->buf_mixpos = 0;
649                 dsb->leadin = FALSE;
650                 DSOUND_CheckEvent(dsb, mixlen);
651         }
652
653         /* Report back the total prebuffered amount for this buffer */
654         return primary_done;
655 }
656
657 /**
658  * For a DirectSoundDevice, go through all the currently playing buffers and
659  * mix them in to the device buffer.
660  *
661  * playpos = the current play position in the primary buffer
662  * writepos = the current safe-to-write position in the primary buffer
663  * mixlen = the maximum amount to mix into the primary buffer
664  *          (beyond the current writepos)
665  * recover = true if the sound device may have been reset and the write
666  *           position in the device buffer changed
667  * all_stopped = reports back if all buffers have stopped
668  *
669  * Returns:  the length beyond the writepos that was mixed to.
670  */
671
672 static DWORD DSOUND_MixToPrimary(const DirectSoundDevice *device, DWORD playpos, DWORD writepos,
673                                  DWORD mixlen, BOOL recover, BOOL *all_stopped)
674 {
675         INT i, len;
676         DWORD minlen = 0;
677         IDirectSoundBufferImpl  *dsb;
678
679         /* unless we find a running buffer, all have stopped */
680         *all_stopped = TRUE;
681
682         TRACE("(%d,%d,%d,%d)\n", playpos, writepos, mixlen, recover);
683         for (i = 0; i < device->nrofbuffers; i++) {
684                 dsb = device->buffers[i];
685
686                 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
687
688                 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
689                         TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
690                         EnterCriticalSection(&(dsb->lock));
691
692                         /* if buffer is stopping it is stopped now */
693                         if (dsb->state == STATE_STOPPING) {
694                                 dsb->state = STATE_STOPPED;
695                                 DSOUND_CheckEvent(dsb, 0);
696                         } else {
697
698                                 /* if recovering, reset the mix position */
699                                 if ((dsb->state == STATE_STARTING) || recover) {
700                                         dsb->primary_mixpos = writepos;
701                                 }
702
703                                 /* mix next buffer into the main buffer */
704                                 len = DSOUND_MixOne(dsb, playpos, writepos, mixlen);
705
706                                 /* if the buffer was starting, it must be playing now */
707                                 if (dsb->state == STATE_STARTING)
708                                         dsb->state = STATE_PLAYING;
709
710                                 /* check if min-len should be initialized */
711                                 if(minlen == 0) minlen = len;
712
713                                 /* record the minimum length mixed from all buffers */
714                                 /* we only want to return the length which *all* buffers have mixed */
715                                 if(len != 0) minlen = (len < minlen) ? len : minlen;
716                         }
717
718                         if(dsb->state != STATE_STOPPED){
719                                 *all_stopped = FALSE;
720                         }
721
722                         LeaveCriticalSection(&(dsb->lock));
723                 }
724         }
725
726         TRACE("Mixed at least %d from all buffers\n", minlen);
727
728         return minlen;
729 }
730
731 /**
732  * Add buffers to the emulated wave device system.
733  *
734  * device = The current dsound playback device
735  * force = If TRUE, the function will buffer up as many frags as possible,
736  *         even though and will ignore the actual state of the primary buffer.
737  *
738  * Returns:  None
739  */
740
741 static void DSOUND_WaveQueue(DirectSoundDevice *device, BOOL force)
742 {
743         DWORD prebuf_frags, wave_writepos, wave_fragpos, i;
744         TRACE("(%p)\n", device);
745
746         /* calculate the current wave frag position */
747         wave_fragpos = (device->pwplay + device->pwqueue) % DS_HEL_FRAGS;
748
749         /* calculte the current wave write position */
750         wave_writepos = wave_fragpos * device->fraglen;
751
752         TRACE("wave_fragpos = %i, wave_writepos = %i, pwqueue = %i, ds_hel_queue= %i\n",
753                 wave_fragpos, wave_writepos, device->pwqueue, ds_hel_queue);
754
755         if(force == FALSE){
756                 /* check remaining prebuffered frags */
757                 prebuf_frags = DSOUND_BufPtrDiff(device->buflen, device->mixpos, wave_writepos);
758                 prebuf_frags = prebuf_frags / device->fraglen;
759         }
760         else{
761                 /* buffer the maximum amount of frags */
762                 prebuf_frags = device->prebuf;
763         }
764
765         /* limit to the queue we have left */
766         if((prebuf_frags + device->pwqueue) > device->prebuf)
767                 prebuf_frags = device->prebuf - device->pwqueue;
768
769         TRACE("prebuf_frags = %i\n", prebuf_frags);
770
771         /* adjust queue */
772         device->pwqueue += prebuf_frags;
773
774         /* get out of CS when calling the wave system */
775         LeaveCriticalSection(&(device->mixlock));
776         /* **** */
777
778         /* queue up the new buffers */
779         for(i=0; i<prebuf_frags; i++){
780                 TRACE("queueing wave buffer %i\n", wave_fragpos);
781                 waveOutWrite(device->hwo, device->pwave[wave_fragpos], sizeof(WAVEHDR));
782                 wave_fragpos++;
783                 wave_fragpos %= DS_HEL_FRAGS;
784         }
785
786         /* **** */
787         EnterCriticalSection(&(device->mixlock));
788
789         TRACE("queue now = %i\n", device->pwqueue);
790 }
791
792 /**
793  * Perform mixing for a Direct Sound device. That is, go through all the
794  * secondary buffers (the sound bites currently playing) and mix them in
795  * to the primary buffer (the device buffer).
796  */
797 static void DSOUND_PerformMix(DirectSoundDevice *device)
798 {
799
800         TRACE("(%p)\n", device);
801
802         /* **** */
803         EnterCriticalSection(&(device->mixlock));
804
805         if (device->priolevel != DSSCL_WRITEPRIMARY) {
806                 BOOL recover = FALSE, all_stopped = FALSE;
807                 DWORD playpos, writepos, writelead, maxq, frag, prebuff_max, prebuff_left, size1, size2;
808                 LPVOID buf1, buf2;
809                 BOOL lock = (device->hwbuf && !(device->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK));
810                 int nfiller;
811
812                 /* the sound of silence */
813                 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
814
815                 /* get the position in the primary buffer */
816                 if (DSOUND_PrimaryGetPosition(device, &playpos, &writepos) != 0){
817                         LeaveCriticalSection(&(device->mixlock));
818                         return;
819                 }
820
821                 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
822                       playpos,writepos,device->playpos,device->mixpos,device->buflen);
823                 assert(device->playpos < device->buflen);
824
825                 /* wipe out just-played sound data */
826                 if (playpos < device->playpos) {
827                         buf1 = device->buffer + device->playpos;
828                         buf2 = device->buffer;
829                         size1 = device->buflen - device->playpos;
830                         size2 = playpos;
831                         if (lock)
832                                 IDsDriverBuffer_Lock(device->hwbuf, &buf1, &size1, &buf2, &size2, device->playpos, size1+size2, 0);
833                         FillMemory(buf1, size1, nfiller);
834                         if (playpos && (!buf2 || !size2))
835                                 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__, device->playpos, device->mixpos, playpos, writepos);
836                         FillMemory(buf2, size2, nfiller);
837                         if (lock)
838                                 IDsDriverBuffer_Unlock(device->hwbuf, buf1, size1, buf2, size2);
839                 } else {
840                         buf1 = device->buffer + device->playpos;
841                         buf2 = NULL;
842                         size1 = playpos - device->playpos;
843                         size2 = 0;
844                         if (lock)
845                                 IDsDriverBuffer_Lock(device->hwbuf, &buf1, &size1, &buf2, &size2, device->playpos, size1+size2, 0);
846                         FillMemory(buf1, size1, nfiller);
847                         if (buf2 && size2)
848                         {
849                                 FIXME("%d: There should be no additional buffer here!!\n", __LINE__);
850                                 FillMemory(buf2, size2, nfiller);
851                         }
852                         if (lock)
853                                 IDsDriverBuffer_Unlock(device->hwbuf, buf1, size1, buf2, size2);
854                 }
855                 device->playpos = playpos;
856
857                 /* calc maximum prebuff */
858                 prebuff_max = (device->prebuf * device->fraglen);
859
860                 /* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
861                 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
862
863                 writelead = DSOUND_BufPtrDiff(device->buflen, writepos, playpos);
864
865                 /* find the maximum we can prebuffer from current write position */
866                 maxq = prebuff_max - prebuff_left;
867                 maxq = (writelead < prebuff_max) ? (prebuff_max - writelead) : 0;
868
869                 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
870                         prebuff_left, device->prebuf, device->fraglen, prebuff_max, writelead);
871
872                 /* check for underrun. underrun occurs when the write position passes the mix position */
873                 if((prebuff_left > prebuff_max) || (device->state == STATE_STOPPED) || (device->state == STATE_STARTING)){
874                         TRACE("Buffer starting or buffer underrun\n");
875
876                         /* recover mixing for all buffers */
877                         recover = TRUE;
878
879                         /* reset mix position to write position */
880                         device->mixpos = writepos;
881                 }
882
883                 if (lock)
884                         IDsDriverBuffer_Lock(device->hwbuf, &buf1, &size1, &buf2, &size2, device->mixpos, maxq, 0);
885
886                 /* do the mixing */
887                 frag = DSOUND_MixToPrimary(device, playpos, writepos, maxq, recover, &all_stopped);
888
889                 /* update the mix position, taking wrap-around into acount */
890                 device->mixpos = writepos + frag;
891                 device->mixpos %= device->buflen;
892
893                 if (lock)
894                 {
895                         DWORD frag2 = (frag > size1 ? frag - size1 : 0);
896                         frag -= frag2;
897                         if (frag2 > size2)
898                         {
899                                 FIXME("Buffering too much! (%d, %d, %d, %d)\n", maxq, frag, size2, frag2 - size2);
900                                 frag2 = size2;
901                         }
902                         IDsDriverBuffer_Unlock(device->hwbuf, buf1, frag, buf2, frag2);
903                 }
904
905                 /* update prebuff left */
906                 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
907
908                 /* check if have a whole fragment */
909                 if (prebuff_left >= device->fraglen){
910
911                         /* update the wave queue if using wave system */
912                         if(device->hwbuf == NULL){
913                                 DSOUND_WaveQueue(device,TRUE);
914                         }
915
916                         /* buffers are full. start playing if applicable */
917                         if(device->state == STATE_STARTING){
918                                 TRACE("started primary buffer\n");
919                                 if(DSOUND_PrimaryPlay(device) != DS_OK){
920                                         WARN("DSOUND_PrimaryPlay failed\n");
921                                 }
922                                 else{
923                                         /* we are playing now */
924                                         device->state = STATE_PLAYING;
925                                 }
926                         }
927
928                         /* buffers are full. start stopping if applicable */
929                         if(device->state == STATE_STOPPED){
930                                 TRACE("restarting primary buffer");
931                                 if(DSOUND_PrimaryPlay(device) != DS_OK){
932                                         WARN("DSOUND_PrimaryPlay failed\n");
933                                 }
934                                 else{
935                                         /* start stopping again. as soon as there is no more data, it will stop */
936                                         device->state = STATE_STOPPING;
937                                 }
938                         }
939                 }
940
941                 /* if device was stopping, its for sure stopped when all buffers have stopped */
942                 else if((all_stopped == TRUE) && (device->state == STATE_STOPPING)){
943                         TRACE("All buffers have stopped. Stopping primary buffer\n");
944                         device->state = STATE_STOPPED;
945
946                         /* stop the primary buffer now */
947                         DSOUND_PrimaryStop(device);
948                 }
949
950         } else {
951
952                 /* update the wave queue if using wave system */
953                 if(device->hwbuf == NULL){
954                         DSOUND_WaveQueue(device, TRUE);
955                 }
956
957                 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
958                 if (device->state == STATE_STARTING) {
959                         if (DSOUND_PrimaryPlay(device) != DS_OK)
960                                 WARN("DSOUND_PrimaryPlay failed\n");
961                         else
962                                 device->state = STATE_PLAYING;
963                 }
964                 else if (device->state == STATE_STOPPING) {
965                         if (DSOUND_PrimaryStop(device) != DS_OK)
966                                 WARN("DSOUND_PrimaryStop failed\n");
967                         else
968                                 device->state = STATE_STOPPED;
969                 }
970         }
971
972         LeaveCriticalSection(&(device->mixlock));
973         /* **** */
974 }
975
976 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD_PTR dwUser,
977                            DWORD_PTR dw1, DWORD_PTR dw2)
978 {
979         DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
980         DWORD start_time =  GetTickCount();
981         DWORD end_time;
982         TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
983         TRACE("entering at %d\n", start_time);
984
985         if (DSOUND_renderer[device->drvdesc.dnDevNode] != device) {
986                 ERR("dsound died without killing us?\n");
987                 timeKillEvent(timerID);
988                 timeEndPeriod(DS_TIME_RES);
989                 return;
990         }
991
992         RtlAcquireResourceShared(&(device->buffer_list_lock), TRUE);
993
994         if (device->ref)
995                 DSOUND_PerformMix(device);
996
997         RtlReleaseResource(&(device->buffer_list_lock));
998
999         end_time = GetTickCount();
1000         TRACE("completed processing at %d, duration = %d\n", end_time, end_time - start_time);
1001 }
1002
1003 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1004 {
1005         DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
1006         TRACE("(%p,%x,%x,%x,%x)\n",hwo,msg,dwUser,dw1,dw2);
1007         TRACE("entering at %d, msg=%08x(%s)\n", GetTickCount(), msg,
1008                 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" : 
1009                 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1010
1011         /* check if packet completed from wave driver */
1012         if (msg == MM_WOM_DONE) {
1013
1014                 /* **** */
1015                 EnterCriticalSection(&(device->mixlock));
1016
1017                 TRACE("done playing primary pos=%d\n", device->pwplay * device->fraglen);
1018
1019                 /* update playpos */
1020                 device->pwplay++;
1021                 device->pwplay %= DS_HEL_FRAGS;
1022
1023                 /* sanity */
1024                 if(device->pwqueue == 0){
1025                         ERR("Wave queue corrupted!\n");
1026                 }
1027
1028                 /* update queue */
1029                 device->pwqueue--;
1030
1031                 LeaveCriticalSection(&(device->mixlock));
1032                 /* **** */
1033         }
1034         TRACE("completed\n");
1035 }