d3dx9/tests: Add effect parameter value SetInt() test.
[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  * Copyright 2007 Maarten Lankhorst
8  * Copyright 2011 Owen Rudge for CodeWeavers
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include <assert.h>
26 #include <stdarg.h>
27 #include <math.h>       /* Insomnia - pow() function */
28
29 #define COBJMACROS
30 #define NONAMELESSSTRUCT
31 #define NONAMELESSUNION
32 #include "windef.h"
33 #include "winbase.h"
34 #include "mmsystem.h"
35 #include "wingdi.h"
36 #include "mmreg.h"
37 #include "winternl.h"
38 #include "wine/debug.h"
39 #include "dsound.h"
40 #include "ks.h"
41 #include "ksmedia.h"
42 #include "dsound_private.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
45
46 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
47 {
48         double temp;
49         TRACE("(%p)\n",volpan);
50
51         TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
52         /* the AmpFactors are expressed in 16.16 fixed point */
53         volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
54         /* FIXME: dwPan{Left|Right}AmpFactor */
55
56         /* FIXME: use calculated vol and pan ampfactors */
57         temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
58         volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
59         temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
60         volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
61
62         TRACE("left = %x, right = %x\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
63 }
64
65 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
66 {
67     double left,right;
68     TRACE("(%p)\n",volpan);
69
70     TRACE("left=%x, right=%x\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
71     if (volpan->dwTotalLeftAmpFactor==0)
72         left=-10000;
73     else
74         left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
75     if (volpan->dwTotalRightAmpFactor==0)
76         right=-10000;
77     else
78         right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
79     if (left<right)
80     {
81         volpan->lVolume=right;
82         volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
83     }
84     else
85     {
86         volpan->lVolume=left;
87         volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
88     }
89     if (volpan->lVolume < -10000)
90         volpan->lVolume=-10000;
91     volpan->lPan=right-left;
92     if (volpan->lPan < -10000)
93         volpan->lPan=-10000;
94
95     TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
96 }
97
98 /** Convert a primary buffer position to a pointer position for device->mix_buffer
99  * device: DirectSoundDevice for which to calculate
100  * pos: Primary buffer position to converts
101  * Returns: Offset for mix_buffer
102  */
103 DWORD DSOUND_bufpos_to_mixpos(const DirectSoundDevice* device, DWORD pos)
104 {
105     DWORD ret = pos * 32 / device->pwfx->wBitsPerSample;
106     if (device->pwfx->wBitsPerSample == 32)
107         ret *= 2;
108     return ret;
109 }
110
111 /* NOTE: Not all secpos have to always be mapped to a bufpos, other way around is always the case
112  * DWORD64 is used here because a single DWORD wouldn't be big enough to fit the freqAcc for big buffers
113  */
114 /** This function converts a 'native' sample pointer to a resampled pointer that fits for primary
115  * secmixpos is used to decide which freqAcc is needed
116  * overshot tells what the 'actual' secpos is now (optional)
117  */
118 DWORD DSOUND_secpos_to_bufpos(const IDirectSoundBufferImpl *dsb, DWORD secpos, DWORD secmixpos, DWORD* overshot)
119 {
120         DWORD64 framelen = secpos / dsb->pwfx->nBlockAlign;
121         DWORD64 freqAdjust = dsb->freqAdjust;
122         DWORD64 acc, freqAcc;
123
124         if (secpos < secmixpos)
125                 freqAcc = dsb->freqAccNext;
126         else freqAcc = dsb->freqAcc;
127         acc = (framelen << DSOUND_FREQSHIFT) + (freqAdjust - 1 - freqAcc);
128         acc /= freqAdjust;
129         if (overshot)
130         {
131                 DWORD64 oshot = acc * freqAdjust + freqAcc;
132                 assert(oshot >= framelen << DSOUND_FREQSHIFT);
133                 oshot -= framelen << DSOUND_FREQSHIFT;
134                 *overshot = (DWORD)oshot;
135                 assert(*overshot < dsb->freqAdjust);
136         }
137         return (DWORD)acc * dsb->device->pwfx->nBlockAlign;
138 }
139
140 /** Convert a resampled pointer that fits for primary to a 'native' sample pointer
141  * freqAccNext is used here rather than freqAcc: In case the app wants to fill up to
142  * the play position it won't overwrite it
143  */
144 static DWORD DSOUND_bufpos_to_secpos(const IDirectSoundBufferImpl *dsb, DWORD bufpos)
145 {
146         DWORD oAdv = dsb->device->pwfx->nBlockAlign, iAdv = dsb->pwfx->nBlockAlign, pos;
147         DWORD64 framelen;
148         DWORD64 acc;
149
150         framelen = bufpos/oAdv;
151         acc = framelen * (DWORD64)dsb->freqAdjust + (DWORD64)dsb->freqAccNext;
152         acc = acc >> DSOUND_FREQSHIFT;
153         pos = (DWORD)acc * iAdv;
154         if (pos >= dsb->buflen)
155                 /* Because of differences between freqAcc and freqAccNext, this might happen */
156                 pos = dsb->buflen - iAdv;
157         TRACE("Converted %d/%d to %d/%d\n", bufpos, dsb->tmp_buffer_len, pos, dsb->buflen);
158         return pos;
159 }
160
161 /**
162  * Move freqAccNext to freqAcc, and find new values for buffer length and freqAccNext
163  */
164 static void DSOUND_RecalcFreqAcc(IDirectSoundBufferImpl *dsb)
165 {
166         if (!dsb->freqneeded) return;
167         dsb->freqAcc = dsb->freqAccNext;
168         dsb->tmp_buffer_len = DSOUND_secpos_to_bufpos(dsb, dsb->buflen, 0, &dsb->freqAccNext);
169         TRACE("New freqadjust: %04x, new buflen: %d\n", dsb->freqAccNext, dsb->tmp_buffer_len);
170 }
171
172 /**
173  * Recalculate the size for temporary buffer, and new writelead
174  * Should be called when one of the following things occur:
175  * - Primary buffer format is changed
176  * - This buffer format (frequency) is changed
177  */
178 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
179 {
180         BOOL needremix = TRUE, needresample = (dsb->freq != dsb->device->pwfx->nSamplesPerSec);
181         DWORD bAlign = dsb->pwfx->nBlockAlign, pAlign = dsb->device->pwfx->nBlockAlign;
182         WAVEFORMATEXTENSIBLE *pwfxe;
183         BOOL ieee = FALSE;
184
185         TRACE("(%p)\n",dsb);
186
187         pwfxe = (WAVEFORMATEXTENSIBLE *) dsb->pwfx;
188
189         if ((pwfxe->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) || ((pwfxe->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
190             && (IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))))
191                 ieee = TRUE;
192
193         /* calculate the 10ms write lead */
194         dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
195
196         if ((dsb->pwfx->wBitsPerSample == dsb->device->pwfx->wBitsPerSample) &&
197             (dsb->pwfx->nChannels == dsb->device->pwfx->nChannels) && !needresample && !ieee)
198                 needremix = FALSE;
199         dsb->freqAcc = dsb->freqAccNext = 0;
200         dsb->freqneeded = needresample;
201
202         if (ieee)
203                 dsb->convert = convertbpp[4][dsb->device->pwfx->wBitsPerSample/8 - 1];
204         else
205                 dsb->convert = convertbpp[dsb->pwfx->wBitsPerSample/8 - 1][dsb->device->pwfx->wBitsPerSample/8 - 1];
206
207         if (needremix)
208         {
209                 if (needresample)
210                         DSOUND_RecalcFreqAcc(dsb);
211                 else
212                         dsb->tmp_buffer_len = dsb->buflen / bAlign * pAlign;
213         }
214         else dsb->tmp_buffer_len = dsb->buflen;
215         dsb->buf_mixpos = DSOUND_secpos_to_bufpos(dsb, dsb->sec_mixpos, 0, NULL);
216 }
217
218 /**
219  * Check for application callback requests for when the play position
220  * reaches certain points.
221  *
222  * The offsets that will be triggered will be those between the recorded
223  * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
224  * beyond that position.
225  */
226 void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
227 {
228         int                     i;
229         DWORD                   offset;
230         LPDSBPOSITIONNOTIFY     event;
231         TRACE("(%p,%d)\n",dsb,len);
232
233         if (dsb->nrofnotifies == 0)
234                 return;
235
236         TRACE("(%p) buflen = %d, playpos = %d, len = %d\n",
237                 dsb, dsb->buflen, playpos, len);
238         for (i = 0; i < dsb->nrofnotifies ; i++) {
239                 event = dsb->notifies + i;
240                 offset = event->dwOffset;
241                 TRACE("checking %d, position %d, event = %p\n",
242                         i, offset, event->hEventNotify);
243                 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
244                 /* OK. [Inside DirectX, p274] */
245                 /* Windows does not seem to enforce this, and some apps rely */
246                 /* on that, so we can't stop there. */
247                 /*  */
248                 /* This also means we can't sort the entries by offset, */
249                 /* because DSBPN_OFFSETSTOP == -1 */
250                 if (offset == DSBPN_OFFSETSTOP) {
251                         if (dsb->state == STATE_STOPPED) {
252                                 SetEvent(event->hEventNotify);
253                                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
254                         }
255                         continue;
256                 }
257                 if ((playpos + len) >= dsb->buflen) {
258                         if ((offset < ((playpos + len) % dsb->buflen)) ||
259                             (offset >= playpos)) {
260                                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
261                                 SetEvent(event->hEventNotify);
262                         }
263                 } else {
264                         if ((offset >= playpos) && (offset < (playpos + len))) {
265                                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
266                                 SetEvent(event->hEventNotify);
267                         }
268                 }
269         }
270 }
271
272 /**
273  * Copy a single frame from the given input buffer to the given output buffer.
274  * Translate 8 <-> 16 bits and mono <-> stereo
275  */
276 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, const BYTE *ibuf, BYTE *obuf,
277         UINT istride, UINT ostride, UINT count, UINT freqAcc, UINT adj)
278 {
279     DirectSoundDevice *device = dsb->device;
280     INT istep = dsb->pwfx->wBitsPerSample / 8, ostep = device->pwfx->wBitsPerSample / 8;
281
282     if (device->pwfx->nChannels == dsb->pwfx->nChannels ||
283         (device->pwfx->nChannels == 2 && dsb->pwfx->nChannels == 6) ||
284         (device->pwfx->nChannels == 8 && dsb->pwfx->nChannels == 2) ||
285         (device->pwfx->nChannels == 6 && dsb->pwfx->nChannels == 2)) {
286         dsb->convert(ibuf, obuf, istride, ostride, count, freqAcc, adj);
287         if (device->pwfx->nChannels == 2 || dsb->pwfx->nChannels == 2)
288             dsb->convert(ibuf + istep, obuf + ostep, istride, ostride, count, freqAcc, adj);
289         return;
290     }
291
292     if (device->pwfx->nChannels == 1 && dsb->pwfx->nChannels == 2)
293     {
294         dsb->convert(ibuf, obuf, istride, ostride, count, freqAcc, adj);
295         return;
296     }
297
298     if (device->pwfx->nChannels == 2 && dsb->pwfx->nChannels == 1)
299     {
300         dsb->convert(ibuf, obuf, istride, ostride, count, freqAcc, adj);
301         dsb->convert(ibuf, obuf + ostep, istride, ostride, count, freqAcc, adj);
302         return;
303     }
304
305     WARN("Unable to remap channels: device=%u, buffer=%u\n", device->pwfx->nChannels,
306             dsb->pwfx->nChannels);
307 }
308
309 /**
310  * Calculate the distance between two buffer offsets, taking wraparound
311  * into account.
312  */
313 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
314 {
315 /* If these asserts fail, the problem is not here, but in the underlying code */
316         assert(ptr1 < buflen);
317         assert(ptr2 < buflen);
318         if (ptr1 >= ptr2) {
319                 return ptr1 - ptr2;
320         } else {
321                 return buflen + ptr1 - ptr2;
322         }
323 }
324 /**
325  * Mix at most the given amount of data into the allocated temporary buffer
326  * of the given secondary buffer, starting from the dsb's first currently
327  * unsampled frame (writepos), translating frequency (pitch), stereo/mono
328  * and bits-per-sample so that it is ideal for the primary buffer.
329  * Doesn't perform any mixing - this is a straight copy/convert operation.
330  *
331  * dsb = the secondary buffer
332  * writepos = Starting position of changed buffer
333  * len = number of bytes to resample from writepos
334  *
335  * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
336  */
337 static void DSOUND_MixToTemporary(const IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
338 {
339         INT     size;
340         BYTE    *ibp, *obp, *obp_begin;
341         INT     iAdvance = dsb->pwfx->nBlockAlign;
342         INT     oAdvance = dsb->device->pwfx->nBlockAlign;
343         DWORD freqAcc, overshot, maxlen;
344
345         assert(writepos + len <= dsb->buflen);
346         if (writepos + len < dsb->buflen)
347                 len += dsb->pwfx->nBlockAlign;
348
349         maxlen = DSOUND_secpos_to_bufpos(dsb, len, 0, NULL);
350
351         ibp = dsb->buffer->memory + writepos;
352         if (dsb->device->tmp_buffer_len < maxlen || !dsb->device->tmp_buffer)
353         {
354                 dsb->device->tmp_buffer_len = maxlen;
355                 if (dsb->device->tmp_buffer)
356                         dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, maxlen);
357                 else
358                         dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, maxlen);
359                 obp_begin = dsb->device->tmp_buffer;
360         }
361         else
362                 obp_begin = dsb->device->tmp_buffer;
363
364         TRACE("(%p, %p)\n", dsb, ibp);
365         size = len / iAdvance;
366
367         /* Check for same sample rate */
368         if (dsb->freq == dsb->device->pwfx->nSamplesPerSec) {
369                 TRACE("(%p) Same sample rate %d = primary %d\n", dsb,
370                         dsb->freq, dsb->device->pwfx->nSamplesPerSec);
371                 obp = obp_begin;
372
373                 cp_fields(dsb, ibp, obp, iAdvance, oAdvance, size, 0, 1 << DSOUND_FREQSHIFT);
374                 return;
375         }
376
377         /* Mix in different sample rates */
378         TRACE("(%p) Adjusting frequency: %d -> %d\n", dsb, dsb->freq, dsb->device->pwfx->nSamplesPerSec);
379
380         DSOUND_secpos_to_bufpos(dsb, writepos, dsb->sec_mixpos, &freqAcc);
381         overshot = freqAcc >> DSOUND_FREQSHIFT;
382         if (overshot)
383         {
384                 if (overshot >= size)
385                         return;
386                 size -= overshot;
387                 writepos += overshot * iAdvance;
388                 if (writepos >= dsb->buflen)
389                         return;
390                 ibp = dsb->buffer->memory + writepos;
391                 freqAcc &= (1 << DSOUND_FREQSHIFT) - 1;
392                 TRACE("Overshot: %d, freqAcc: %04x\n", overshot, freqAcc);
393         }
394
395         obp = obp_begin;
396
397         /* FIXME: Small problem here when we're overwriting buf_mixpos, it then STILL uses old freqAcc, not sure if it matters or not */
398         cp_fields(dsb, ibp, obp, iAdvance, oAdvance, size, freqAcc, dsb->freqAdjust);
399 }
400
401 /** Apply volume to the given soundbuffer from (primary) position writepos and length len
402  * Returns: NULL if no volume needs to be applied
403  * or else a memory handle that holds 'len' volume adjusted buffer */
404 static LPBYTE DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT len)
405 {
406         INT     i;
407         BYTE    *bpc;
408         INT16   *bps, *mems;
409         DWORD vLeft, vRight;
410         INT nChannels = dsb->device->pwfx->nChannels;
411         LPBYTE mem = dsb->device->tmp_buffer;
412
413         TRACE("(%p,%d)\n",dsb,len);
414         TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalLeftAmpFactor,
415                 dsb->volpan.dwTotalRightAmpFactor);
416
417         if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
418             (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
419              !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
420                 return NULL; /* Nothing to do */
421
422         if (nChannels != 1 && nChannels != 2)
423         {
424                 FIXME("There is no support for %d channels\n", nChannels);
425                 return NULL;
426         }
427
428         if (dsb->device->pwfx->wBitsPerSample != 8 && dsb->device->pwfx->wBitsPerSample != 16)
429         {
430                 FIXME("There is no support for %d bpp\n", dsb->device->pwfx->wBitsPerSample);
431                 return NULL;
432         }
433
434         assert(dsb->device->tmp_buffer_len >= len && dsb->device->tmp_buffer);
435
436         bpc = dsb->device->tmp_buffer;
437         bps = (INT16 *)bpc;
438         mems = (INT16 *)mem;
439         vLeft = dsb->volpan.dwTotalLeftAmpFactor;
440         if (nChannels > 1)
441                 vRight = dsb->volpan.dwTotalRightAmpFactor;
442         else
443                 vRight = vLeft;
444
445         switch (dsb->device->pwfx->wBitsPerSample) {
446         case 8:
447                 /* 8-bit WAV is unsigned, but we need to operate */
448                 /* on signed data for this to work properly */
449                 for (i = 0; i < len-1; i+=2) {
450                         *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
451                         *(bpc++) = (((*(mem++) - 128) * vRight) >> 16) + 128;
452                 }
453                 if (len % 2 == 1 && nChannels == 1)
454                         *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
455                 break;
456         case 16:
457                 /* 16-bit WAV is signed -- much better */
458                 for (i = 0; i < len-3; i += 4) {
459                         *(bps++) = (*(mems++) * vLeft) >> 16;
460                         *(bps++) = (*(mems++) * vRight) >> 16;
461                 }
462                 if (len % 4 == 2 && nChannels == 1)
463                         *(bps++) = ((INT)*(mems++) * vLeft) >> 16;
464                 break;
465         }
466         return dsb->device->tmp_buffer;
467 }
468
469 /**
470  * Mix (at most) the given number of bytes into the given position of the
471  * device buffer, from the secondary buffer "dsb" (starting at the current
472  * mix position for that buffer).
473  *
474  * Returns the number of bytes actually mixed into the device buffer. This
475  * will match fraglen unless the end of the secondary buffer is reached
476  * (and it is not looping).
477  *
478  * dsb  = the secondary buffer to mix from
479  * writepos = position (offset) in device buffer to write at
480  * fraglen = number of bytes to mix
481  */
482 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
483 {
484         INT len = fraglen, ilen;
485         BYTE *ibuf = dsb->buffer->memory + dsb->buf_mixpos, *volbuf;
486         DWORD oldpos, mixbufpos;
487
488         TRACE("buf_mixpos=%d/%d sec_mixpos=%d/%d\n", dsb->buf_mixpos, dsb->tmp_buffer_len, dsb->sec_mixpos, dsb->buflen);
489         TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
490
491         assert(dsb->buf_mixpos + len <= dsb->tmp_buffer_len);
492
493         if (len % dsb->device->pwfx->nBlockAlign) {
494                 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
495                 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
496                 len -= len % nBlockAlign; /* data alignment */
497         }
498
499         /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
500         DSOUND_MixToTemporary(dsb, dsb->sec_mixpos, DSOUND_bufpos_to_secpos(dsb, dsb->buf_mixpos+len) - dsb->sec_mixpos);
501         ibuf = dsb->device->tmp_buffer;
502
503         /* Apply volume if needed */
504         volbuf = DSOUND_MixerVol(dsb, len);
505         if (volbuf)
506                 ibuf = volbuf;
507
508         mixbufpos = DSOUND_bufpos_to_mixpos(dsb->device, writepos);
509         /* Now mix the temporary buffer into the devices main buffer */
510         if ((writepos + len) <= dsb->device->buflen)
511                 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, len);
512         else
513         {
514                 DWORD todo = dsb->device->buflen - writepos;
515                 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, todo);
516                 dsb->device->mixfunction(ibuf + todo, dsb->device->mix_buffer, len - todo);
517         }
518
519         oldpos = dsb->sec_mixpos;
520         dsb->buf_mixpos += len;
521
522         if (dsb->buf_mixpos >= dsb->tmp_buffer_len) {
523                 if (dsb->playflags & DSBPLAY_LOOPING) {
524                         dsb->buf_mixpos -= dsb->tmp_buffer_len;
525                 } else {
526                         dsb->buf_mixpos = dsb->sec_mixpos = 0;
527                         dsb->state = STATE_STOPPED;
528                 }
529                 DSOUND_RecalcFreqAcc(dsb);
530         }
531
532         dsb->sec_mixpos = DSOUND_bufpos_to_secpos(dsb, dsb->buf_mixpos);
533         ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
534         /* check for notification positions */
535         if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
536             dsb->state != STATE_STARTING) {
537                 DSOUND_CheckEvent(dsb, oldpos, ilen);
538         }
539
540         /* increase mix position */
541         dsb->primary_mixpos += len;
542         if (dsb->primary_mixpos >= dsb->device->buflen)
543                 dsb->primary_mixpos -= dsb->device->buflen;
544         return len;
545 }
546
547 /**
548  * Mix some frames from the given secondary buffer "dsb" into the device
549  * primary buffer.
550  *
551  * dsb = the secondary buffer
552  * playpos = the current play position in the device buffer (primary buffer)
553  * writepos = the current safe-to-write position in the device buffer
554  * mixlen = the maximum number of bytes in the primary buffer to mix, from the
555  *          current writepos.
556  *
557  * Returns: the number of bytes beyond the writepos that were mixed.
558  */
559 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD mixlen)
560 {
561         /* The buffer's primary_mixpos may be before or after the device
562          * buffer's mixpos, but both must be ahead of writepos. */
563         DWORD primary_done;
564
565         TRACE("(%p,%d,%d)\n",dsb,writepos,mixlen);
566         TRACE("writepos=%d, buf_mixpos=%d, primary_mixpos=%d, mixlen=%d\n", writepos, dsb->buf_mixpos, dsb->primary_mixpos, mixlen);
567         TRACE("looping=%d, leadin=%d, buflen=%d\n", dsb->playflags, dsb->leadin, dsb->tmp_buffer_len);
568
569         /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
570         if (dsb->leadin && dsb->state == STATE_STARTING)
571         {
572                 if (mixlen > 2 * dsb->device->fraglen)
573                 {
574                         dsb->primary_mixpos += mixlen - 2 * dsb->device->fraglen;
575                         dsb->primary_mixpos %= dsb->device->buflen;
576                 }
577         }
578         dsb->leadin = FALSE;
579
580         /* calculate how much pre-buffering has already been done for this buffer */
581         primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
582
583         /* sanity */
584         if(mixlen < primary_done)
585         {
586                 /* Should *NEVER* happen */
587                 ERR("Fatal error. Under/Overflow? primary_done=%d, mixpos=%d/%d (%d/%d), primary_mixpos=%d, writepos=%d, mixlen=%d\n", primary_done,dsb->buf_mixpos,dsb->tmp_buffer_len,dsb->sec_mixpos, dsb->buflen, dsb->primary_mixpos, writepos, mixlen);
588                 dsb->primary_mixpos = writepos + mixlen;
589                 dsb->primary_mixpos %= dsb->device->buflen;
590                 return mixlen;
591         }
592
593         /* take into account already mixed data */
594         mixlen -= primary_done;
595
596         TRACE("primary_done=%d, mixlen (primary) = %i\n", primary_done, mixlen);
597
598         if (!mixlen)
599                 return primary_done;
600
601         /* First try to mix to the end of the buffer if possible
602          * Theoretically it would allow for better optimization
603         */
604         if (mixlen + dsb->buf_mixpos >= dsb->tmp_buffer_len)
605         {
606                 DWORD newmixed, mixfirst = dsb->tmp_buffer_len - dsb->buf_mixpos;
607                 newmixed = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixfirst);
608                 mixlen -= newmixed;
609
610                 if (dsb->playflags & DSBPLAY_LOOPING)
611                         while (newmixed && mixlen)
612                         {
613                                 mixfirst = (dsb->tmp_buffer_len < mixlen ? dsb->tmp_buffer_len : mixlen);
614                                 newmixed = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixfirst);
615                                 mixlen -= newmixed;
616                         }
617         }
618         else DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixlen);
619
620         /* re-calculate the primary done */
621         primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
622
623         TRACE("new primary_mixpos=%d, total mixed data=%d\n", dsb->primary_mixpos, primary_done);
624
625         /* Report back the total prebuffered amount for this buffer */
626         return primary_done;
627 }
628
629 /**
630  * For a DirectSoundDevice, go through all the currently playing buffers and
631  * mix them in to the device buffer.
632  *
633  * writepos = the current safe-to-write position in the primary buffer
634  * mixlen = the maximum amount to mix into the primary buffer
635  *          (beyond the current writepos)
636  * recover = true if the sound device may have been reset and the write
637  *           position in the device buffer changed
638  * all_stopped = reports back if all buffers have stopped
639  *
640  * Returns:  the length beyond the writepos that was mixed to.
641  */
642
643 static DWORD DSOUND_MixToPrimary(const DirectSoundDevice *device, DWORD writepos, DWORD mixlen, BOOL recover, BOOL *all_stopped)
644 {
645         INT i, len;
646         DWORD minlen = 0;
647         IDirectSoundBufferImpl  *dsb;
648
649         /* unless we find a running buffer, all have stopped */
650         *all_stopped = TRUE;
651
652         TRACE("(%d,%d,%d)\n", writepos, mixlen, recover);
653         for (i = 0; i < device->nrofbuffers; i++) {
654                 dsb = device->buffers[i];
655
656                 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
657
658                 if (dsb->buflen && dsb->state) {
659                         TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
660                         RtlAcquireResourceShared(&dsb->lock, TRUE);
661                         /* if buffer is stopping it is stopped now */
662                         if (dsb->state == STATE_STOPPING) {
663                                 dsb->state = STATE_STOPPED;
664                                 DSOUND_CheckEvent(dsb, 0, 0);
665                         } else if (dsb->state != STATE_STOPPED) {
666
667                                 /* if recovering, reset the mix position */
668                                 if ((dsb->state == STATE_STARTING) || recover) {
669                                         dsb->primary_mixpos = writepos;
670                                 }
671
672                                 /* if the buffer was starting, it must be playing now */
673                                 if (dsb->state == STATE_STARTING)
674                                         dsb->state = STATE_PLAYING;
675
676                                 /* mix next buffer into the main buffer */
677                                 len = DSOUND_MixOne(dsb, writepos, mixlen);
678
679                                 if (!minlen) minlen = len;
680
681                                 /* record the minimum length mixed from all buffers */
682                                 /* we only want to return the length which *all* buffers have mixed */
683                                 else if (len) minlen = (len < minlen) ? len : minlen;
684
685                                 *all_stopped = FALSE;
686                         }
687                         RtlReleaseResource(&dsb->lock);
688                 }
689         }
690
691         TRACE("Mixed at least %d from all buffers\n", minlen);
692         return minlen;
693 }
694
695 /**
696  * Add buffers to the emulated wave device system.
697  *
698  * device = The current dsound playback device
699  * force = If TRUE, the function will buffer up as many frags as possible,
700  *         even though and will ignore the actual state of the primary buffer.
701  *
702  * Returns:  None
703  */
704
705 static void DSOUND_WaveQueue(DirectSoundDevice *device, BOOL force)
706 {
707         DWORD prebuf_frames, buf_offs_bytes, wave_fragpos;
708         int prebuf_frags;
709         BYTE *buffer;
710         HRESULT hr;
711
712         TRACE("(%p)\n", device);
713
714         /* calculate the current wave frag position */
715         wave_fragpos = (device->pwplay + device->pwqueue) % device->helfrags;
716
717         /* calculate the current wave write position */
718         buf_offs_bytes = wave_fragpos * device->fraglen;
719
720         TRACE("wave_fragpos = %i, buf_offs_bytes = %i, pwqueue = %i, prebuf = %i\n",
721                 wave_fragpos, buf_offs_bytes, device->pwqueue, device->prebuf);
722
723         if (!force)
724         {
725                 /* check remaining prebuffered frags */
726                 prebuf_frags = device->mixpos / device->fraglen;
727                 if (prebuf_frags == device->helfrags)
728                         --prebuf_frags;
729                 TRACE("wave_fragpos = %d, mixpos_frags = %d\n", wave_fragpos, prebuf_frags);
730                 if (prebuf_frags < wave_fragpos)
731                         prebuf_frags += device->helfrags;
732                 prebuf_frags -= wave_fragpos;
733                 TRACE("wanted prebuf_frags = %d\n", prebuf_frags);
734         }
735         else
736                 /* buffer the maximum amount of frags */
737                 prebuf_frags = device->prebuf;
738
739         /* limit to the queue we have left */
740         if ((prebuf_frags + device->pwqueue) > device->prebuf)
741                 prebuf_frags = device->prebuf - device->pwqueue;
742
743         TRACE("prebuf_frags = %i\n", prebuf_frags);
744
745         if(!prebuf_frags)
746                 return;
747
748         /* adjust queue */
749         device->pwqueue += prebuf_frags;
750
751         prebuf_frames = ((prebuf_frags + wave_fragpos > device->helfrags) ?
752                         (device->helfrags - wave_fragpos) :
753                         (prebuf_frags)) * device->fraglen / device->pwfx->nBlockAlign;
754
755         hr = IAudioRenderClient_GetBuffer(device->render, prebuf_frames, &buffer);
756         if(FAILED(hr)){
757                 WARN("GetBuffer failed: %08x\n", hr);
758                 return;
759         }
760
761         memcpy(buffer, device->buffer + buf_offs_bytes,
762                         prebuf_frames * device->pwfx->nBlockAlign);
763
764         hr = IAudioRenderClient_ReleaseBuffer(device->render, prebuf_frames, 0);
765         if(FAILED(hr)){
766                 WARN("ReleaseBuffer failed: %08x\n", hr);
767                 return;
768         }
769
770         /* check if anything wrapped */
771         prebuf_frags = prebuf_frags + wave_fragpos - device->helfrags;
772         if(prebuf_frags > 0){
773                 prebuf_frames = prebuf_frags * device->fraglen / device->pwfx->nBlockAlign;
774
775                 hr = IAudioRenderClient_GetBuffer(device->render, prebuf_frames, &buffer);
776                 if(FAILED(hr)){
777                         WARN("GetBuffer failed: %08x\n", hr);
778                         return;
779                 }
780
781                 memcpy(buffer, device->buffer, prebuf_frames * device->pwfx->nBlockAlign);
782
783                 hr = IAudioRenderClient_ReleaseBuffer(device->render, prebuf_frames, 0);
784                 if(FAILED(hr)){
785                         WARN("ReleaseBuffer failed: %08x\n", hr);
786                         return;
787                 }
788         }
789
790         TRACE("queue now = %i\n", device->pwqueue);
791 }
792
793 /**
794  * Perform mixing for a Direct Sound device. That is, go through all the
795  * secondary buffers (the sound bites currently playing) and mix them in
796  * to the primary buffer (the device buffer).
797  */
798 static void DSOUND_PerformMix(DirectSoundDevice *device)
799 {
800         UINT64 clock_pos, clock_freq, pos_bytes;
801         UINT delta_frags;
802         HRESULT hr;
803
804         TRACE("(%p)\n", device);
805
806         /* **** */
807         EnterCriticalSection(&device->mixlock);
808
809         hr = IAudioClock_GetFrequency(device->clock, &clock_freq);
810         if(FAILED(hr)){
811                 WARN("GetFrequency failed: %08x\n", hr);
812         LeaveCriticalSection(&device->mixlock);
813                 return;
814         }
815
816         hr = IAudioClock_GetPosition(device->clock, &clock_pos, NULL);
817         if(FAILED(hr)){
818                 WARN("GetCurrentPadding failed: %08x\n", hr);
819         LeaveCriticalSection(&device->mixlock);
820                 return;
821         }
822
823         pos_bytes = (clock_pos * device->pwfx->nSamplesPerSec * device->pwfx->nBlockAlign) / clock_freq;
824
825         delta_frags = (pos_bytes - device->last_pos_bytes) / device->fraglen;
826         if(delta_frags > 0){
827                 device->pwplay += delta_frags;
828                 device->pwplay %= device->helfrags;
829                 device->pwqueue -= delta_frags;
830                 device->last_pos_bytes = pos_bytes - (pos_bytes % device->fraglen);
831         }
832
833         if (device->priolevel != DSSCL_WRITEPRIMARY) {
834                 BOOL recover = FALSE, all_stopped = FALSE;
835                 DWORD playpos, writepos, writelead, maxq, frag, prebuff_max, prebuff_left, size1, size2, mixplaypos, mixplaypos2;
836                 LPVOID buf1, buf2;
837                 int nfiller;
838
839                 /* the sound of silence */
840                 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
841
842                 /* get the position in the primary buffer */
843                 if (DSOUND_PrimaryGetPosition(device, &playpos, &writepos) != 0){
844                         LeaveCriticalSection(&(device->mixlock));
845                         return;
846                 }
847
848                 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
849                         playpos,writepos,device->playpos,device->mixpos,device->buflen);
850                 assert(device->playpos < device->buflen);
851
852                 mixplaypos = DSOUND_bufpos_to_mixpos(device, device->playpos);
853                 mixplaypos2 = DSOUND_bufpos_to_mixpos(device, playpos);
854
855                 /* calc maximum prebuff */
856                 prebuff_max = (device->prebuf * device->fraglen);
857                 if (playpos + prebuff_max >= device->helfrags * device->fraglen)
858                         prebuff_max += device->buflen - device->helfrags * 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                 writelead = DSOUND_BufPtrDiff(device->buflen, writepos, playpos);
863
864                 /* check for underrun. underrun occurs when the write position passes the mix position
865                  * also wipe out just-played sound data */
866                 if((prebuff_left > prebuff_max) || (device->state == STATE_STOPPED) || (device->state == STATE_STARTING)){
867                         if (device->state == STATE_STOPPING || device->state == STATE_PLAYING)
868                                 WARN("Probable buffer underrun\n");
869                         else TRACE("Buffer starting or buffer underrun\n");
870
871                         /* recover mixing for all buffers */
872                         recover = TRUE;
873
874                         /* reset mix position to write position */
875                         device->mixpos = writepos;
876
877                         ZeroMemory(device->mix_buffer, device->mix_buffer_len);
878                         ZeroMemory(device->buffer, device->buflen);
879                 } else if (playpos < device->playpos) {
880                         buf1 = device->buffer + device->playpos;
881                         buf2 = device->buffer;
882                         size1 = device->buflen - device->playpos;
883                         size2 = playpos;
884                         FillMemory(device->mix_buffer + mixplaypos, device->mix_buffer_len - mixplaypos, 0);
885                         FillMemory(device->mix_buffer, mixplaypos2, 0);
886                         FillMemory(buf1, size1, nfiller);
887                         if (playpos && (!buf2 || !size2))
888                                 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__, device->playpos, device->mixpos, playpos, writepos);
889                         FillMemory(buf2, size2, nfiller);
890                 } else {
891                         buf1 = device->buffer + device->playpos;
892                         buf2 = NULL;
893                         size1 = playpos - device->playpos;
894                         size2 = 0;
895                         FillMemory(device->mix_buffer + mixplaypos, mixplaypos2 - mixplaypos, 0);
896                         FillMemory(buf1, size1, nfiller);
897                 }
898                 device->playpos = playpos;
899
900                 /* find the maximum we can prebuffer from current write position */
901                 maxq = (writelead < prebuff_max) ? (prebuff_max - writelead) : 0;
902
903                 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
904                         prebuff_left, device->prebuf, device->fraglen, prebuff_max, writelead);
905
906                 /* do the mixing */
907                 frag = DSOUND_MixToPrimary(device, writepos, maxq, recover, &all_stopped);
908
909                 if (frag + writepos > device->buflen)
910                 {
911                         DWORD todo = device->buflen - writepos;
912                         device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, todo);
913                         device->normfunction(device->mix_buffer, device->buffer, frag - todo);
914                 }
915                 else
916                         device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, frag);
917
918                 /* update the mix position, taking wrap-around into account */
919                 device->mixpos = writepos + frag;
920                 device->mixpos %= device->buflen;
921
922                 /* update prebuff left */
923                 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
924
925                 /* check if have a whole fragment */
926                 if (prebuff_left >= device->fraglen){
927
928                         /* update the wave queue */
929                         DSOUND_WaveQueue(device, FALSE);
930
931                         /* buffers are full. start playing if applicable */
932                         if(device->state == STATE_STARTING){
933                                 TRACE("started primary buffer\n");
934                                 if(DSOUND_PrimaryPlay(device) != DS_OK){
935                                         WARN("DSOUND_PrimaryPlay failed\n");
936                                 }
937                                 else{
938                                         /* we are playing now */
939                                         device->state = STATE_PLAYING;
940                                 }
941                         }
942
943                         /* buffers are full. start stopping if applicable */
944                         if(device->state == STATE_STOPPED){
945                                 TRACE("restarting primary buffer\n");
946                                 if(DSOUND_PrimaryPlay(device) != DS_OK){
947                                         WARN("DSOUND_PrimaryPlay failed\n");
948                                 }
949                                 else{
950                                         /* start stopping again. as soon as there is no more data, it will stop */
951                                         device->state = STATE_STOPPING;
952                                 }
953                         }
954                 }
955
956                 /* if device was stopping, its for sure stopped when all buffers have stopped */
957                 else if((all_stopped == TRUE) && (device->state == STATE_STOPPING)){
958                         TRACE("All buffers have stopped. Stopping primary buffer\n");
959                         device->state = STATE_STOPPED;
960
961                         /* stop the primary buffer now */
962                         DSOUND_PrimaryStop(device);
963                 }
964
965         } else {
966
967                 DSOUND_WaveQueue(device, TRUE);
968
969                 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
970                 if (device->state == STATE_STARTING) {
971                         if (DSOUND_PrimaryPlay(device) != DS_OK)
972                                 WARN("DSOUND_PrimaryPlay failed\n");
973                         else
974                                 device->state = STATE_PLAYING;
975                 }
976                 else if (device->state == STATE_STOPPING) {
977                         if (DSOUND_PrimaryStop(device) != DS_OK)
978                                 WARN("DSOUND_PrimaryStop failed\n");
979                         else
980                                 device->state = STATE_STOPPED;
981                 }
982         }
983
984         LeaveCriticalSection(&(device->mixlock));
985         /* **** */
986 }
987
988 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD_PTR dwUser,
989                            DWORD_PTR dw1, DWORD_PTR dw2)
990 {
991         DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
992         DWORD start_time =  GetTickCount();
993         DWORD end_time;
994         TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
995         TRACE("entering at %d\n", start_time);
996
997         RtlAcquireResourceShared(&(device->buffer_list_lock), TRUE);
998
999         if (device->ref)
1000                 DSOUND_PerformMix(device);
1001
1002         RtlReleaseResource(&(device->buffer_list_lock));
1003
1004         end_time = GetTickCount();
1005         TRACE("completed processing at %d, duration = %d\n", end_time, end_time - start_time);
1006 }