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