dmusic: COM cleanup of IDirectMusic8.
[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 /**
112  * Recalculate the size for temporary buffer, and new writelead
113  * Should be called when one of the following things occur:
114  * - Primary buffer format is changed
115  * - This buffer format (frequency) is changed
116  */
117 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
118 {
119         DWORD ichannels = dsb->pwfx->nChannels;
120         DWORD ochannels = dsb->device->pwfx->nChannels;
121         WAVEFORMATEXTENSIBLE *pwfxe;
122         BOOL ieee = FALSE;
123
124         TRACE("(%p)\n",dsb);
125
126         pwfxe = (WAVEFORMATEXTENSIBLE *) dsb->pwfx;
127
128         if ((pwfxe->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) || ((pwfxe->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
129             && (IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))))
130                 ieee = TRUE;
131
132         /* calculate the 10ms write lead */
133         dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
134
135         dsb->freqAcc = 0;
136
137         dsb->get_aux = ieee ? getbpp[4] : getbpp[dsb->pwfx->wBitsPerSample/8 - 1];
138         dsb->put_aux = putbpp[dsb->device->pwfx->wBitsPerSample/8 - 1];
139
140         dsb->get = dsb->get_aux;
141         dsb->put = dsb->put_aux;
142
143         if (ichannels == ochannels)
144         {
145                 dsb->mix_channels = ichannels;
146                 if (ichannels > 32) {
147                         FIXME("Copying %u channels is unsupported, limiting to first 32\n", ichannels);
148                         dsb->mix_channels = 32;
149                 }
150         }
151         else if (ichannels == 1)
152         {
153                 dsb->mix_channels = 1;
154                 dsb->put = put_mono2stereo;
155         }
156         else if (ochannels == 1)
157         {
158                 dsb->mix_channels = 1;
159                 dsb->get = get_mono;
160         }
161         else
162         {
163                 if (ichannels > 2)
164                         FIXME("Conversion from %u to %u channels is not implemented, falling back to stereo\n", ichannels, ochannels);
165                 dsb->mix_channels = 2;
166         }
167 }
168
169 /**
170  * Check for application callback requests for when the play position
171  * reaches certain points.
172  *
173  * The offsets that will be triggered will be those between the recorded
174  * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
175  * beyond that position.
176  */
177 void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
178 {
179         int                     i;
180         DWORD                   offset;
181         LPDSBPOSITIONNOTIFY     event;
182         TRACE("(%p,%d)\n",dsb,len);
183
184         if (dsb->nrofnotifies == 0)
185                 return;
186
187         TRACE("(%p) buflen = %d, playpos = %d, len = %d\n",
188                 dsb, dsb->buflen, playpos, len);
189         for (i = 0; i < dsb->nrofnotifies ; i++) {
190                 event = dsb->notifies + i;
191                 offset = event->dwOffset;
192                 TRACE("checking %d, position %d, event = %p\n",
193                         i, offset, event->hEventNotify);
194                 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
195                 /* OK. [Inside DirectX, p274] */
196                 /* Windows does not seem to enforce this, and some apps rely */
197                 /* on that, so we can't stop there. */
198                 /*  */
199                 /* This also means we can't sort the entries by offset, */
200                 /* because DSBPN_OFFSETSTOP == -1 */
201                 if (offset == DSBPN_OFFSETSTOP) {
202                         if (dsb->state == STATE_STOPPED) {
203                                 SetEvent(event->hEventNotify);
204                                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
205                         }
206                         continue;
207                 }
208                 if ((playpos + len) >= dsb->buflen) {
209                         if ((offset < ((playpos + len) % dsb->buflen)) ||
210                             (offset >= playpos)) {
211                                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
212                                 SetEvent(event->hEventNotify);
213                         }
214                 } else {
215                         if ((offset >= playpos) && (offset < (playpos + len))) {
216                                 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
217                                 SetEvent(event->hEventNotify);
218                         }
219                 }
220         }
221 }
222
223 static inline float get_current_sample(const IDirectSoundBufferImpl *dsb,
224         DWORD mixpos, DWORD channel)
225 {
226     if (mixpos >= dsb->buflen && !(dsb->playflags & DSBPLAY_LOOPING))
227         return 0.0f;
228     return dsb->get(dsb, mixpos % dsb->buflen, channel);
229 }
230
231 /**
232  * Copy frames from the given input buffer to the given output buffer.
233  * Translate 8 <-> 16 bits and mono <-> stereo
234  */
235 static inline void cp_fields(IDirectSoundBufferImpl *dsb,
236         UINT ostride, UINT count, float *freqAcc)
237 {
238     DWORD ipos = dsb->sec_mixpos;
239     UINT istride = dsb->pwfx->nBlockAlign, i;
240     DWORD opos = 0;
241
242     for (i = 0; i < count; ++i){
243         DWORD channel;
244         for (channel = 0; channel < dsb->mix_channels; channel++)
245             dsb->put(dsb, opos, channel,
246                 get_current_sample(dsb, ipos, channel));
247         *freqAcc += dsb->freqAdjust;
248         ipos += ((DWORD)*freqAcc) * istride;
249         *freqAcc -= truncf(*freqAcc);
250         opos += ostride;
251     }
252
253     if (ipos >= dsb->buflen) {
254         if (dsb->playflags & DSBPLAY_LOOPING)
255             ipos %= dsb->buflen;
256         else {
257             ipos = 0;
258             dsb->state = STATE_STOPPED;
259         }
260     }
261
262     dsb->sec_mixpos = ipos;
263 }
264
265 /**
266  * Calculate the distance between two buffer offsets, taking wraparound
267  * into account.
268  */
269 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
270 {
271 /* If these asserts fail, the problem is not here, but in the underlying code */
272         assert(ptr1 < buflen);
273         assert(ptr2 < buflen);
274         if (ptr1 >= ptr2) {
275                 return ptr1 - ptr2;
276         } else {
277                 return buflen + ptr1 - ptr2;
278         }
279 }
280 /**
281  * Mix at most the given amount of data into the allocated temporary buffer
282  * of the given secondary buffer, starting from the dsb's first currently
283  * unsampled frame (writepos), translating frequency (pitch), stereo/mono
284  * and bits-per-sample so that it is ideal for the primary buffer.
285  * Doesn't perform any mixing - this is a straight copy/convert operation.
286  *
287  * dsb = the secondary buffer
288  * writepos = Starting position of changed buffer
289  * len = number of bytes to resample from writepos
290  *
291  * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
292  */
293 static void DSOUND_MixToTemporary(IDirectSoundBufferImpl *dsb, DWORD tmp_len)
294 {
295         INT     oAdvance = dsb->device->pwfx->nBlockAlign;
296         INT     size = tmp_len / oAdvance;
297
298         if (dsb->device->tmp_buffer_len < tmp_len || !dsb->device->tmp_buffer)
299         {
300                 dsb->device->tmp_buffer_len = tmp_len;
301                 if (dsb->device->tmp_buffer)
302                         dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, tmp_len);
303                 else
304                         dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, tmp_len);
305         }
306
307         cp_fields(dsb, oAdvance, size, &dsb->freqAcc);
308 }
309
310 /** Apply volume to the given soundbuffer from (primary) position writepos and length len
311  * Returns: NULL if no volume needs to be applied
312  * or else a memory handle that holds 'len' volume adjusted buffer */
313 static LPBYTE DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT len)
314 {
315         INT     i;
316         BYTE    *bpc;
317         INT16   *bps, *mems;
318         DWORD vLeft, vRight;
319         INT nChannels = dsb->device->pwfx->nChannels;
320         LPBYTE mem = dsb->device->tmp_buffer;
321
322         TRACE("(%p,%d)\n",dsb,len);
323         TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalLeftAmpFactor,
324                 dsb->volpan.dwTotalRightAmpFactor);
325
326         if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
327             (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
328              !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
329                 return NULL; /* Nothing to do */
330
331         if (nChannels != 1 && nChannels != 2)
332         {
333                 FIXME("There is no support for %d channels\n", nChannels);
334                 return NULL;
335         }
336
337         if (dsb->device->pwfx->wBitsPerSample != 8 && dsb->device->pwfx->wBitsPerSample != 16)
338         {
339                 FIXME("There is no support for %d bpp\n", dsb->device->pwfx->wBitsPerSample);
340                 return NULL;
341         }
342
343         assert(dsb->device->tmp_buffer_len >= len && dsb->device->tmp_buffer);
344
345         bpc = dsb->device->tmp_buffer;
346         bps = (INT16 *)bpc;
347         mems = (INT16 *)mem;
348         vLeft = dsb->volpan.dwTotalLeftAmpFactor;
349         if (nChannels > 1)
350                 vRight = dsb->volpan.dwTotalRightAmpFactor;
351         else
352                 vRight = vLeft;
353
354         switch (dsb->device->pwfx->wBitsPerSample) {
355         case 8:
356                 /* 8-bit WAV is unsigned, but we need to operate */
357                 /* on signed data for this to work properly */
358                 for (i = 0; i < len-1; i+=2) {
359                         *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
360                         *(bpc++) = (((*(mem++) - 128) * vRight) >> 16) + 128;
361                 }
362                 if (len % 2 == 1 && nChannels == 1)
363                         *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
364                 break;
365         case 16:
366                 /* 16-bit WAV is signed -- much better */
367                 for (i = 0; i < len-3; i += 4) {
368                         *(bps++) = (*(mems++) * vLeft) >> 16;
369                         *(bps++) = (*(mems++) * vRight) >> 16;
370                 }
371                 if (len % 4 == 2 && nChannels == 1)
372                         *(bps++) = ((INT)*(mems++) * vLeft) >> 16;
373                 break;
374         }
375         return dsb->device->tmp_buffer;
376 }
377
378 /**
379  * Mix (at most) the given number of bytes into the given position of the
380  * device buffer, from the secondary buffer "dsb" (starting at the current
381  * mix position for that buffer).
382  *
383  * Returns the number of bytes actually mixed into the device buffer. This
384  * will match fraglen unless the end of the secondary buffer is reached
385  * (and it is not looping).
386  *
387  * dsb  = the secondary buffer to mix from
388  * writepos = position (offset) in device buffer to write at
389  * fraglen = number of bytes to mix
390  */
391 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
392 {
393         INT len = fraglen;
394         BYTE *ibuf, *volbuf;
395         DWORD oldpos, mixbufpos;
396
397         TRACE("sec_mixpos=%d/%d\n", dsb->sec_mixpos, dsb->buflen);
398         TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
399
400         if (len % dsb->device->pwfx->nBlockAlign) {
401                 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
402                 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
403                 len -= len % nBlockAlign; /* data alignment */
404         }
405
406         /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
407         oldpos = dsb->sec_mixpos;
408
409         DSOUND_MixToTemporary(dsb, len);
410         ibuf = dsb->device->tmp_buffer;
411
412         /* Apply volume if needed */
413         volbuf = DSOUND_MixerVol(dsb, len);
414         if (volbuf)
415                 ibuf = volbuf;
416
417         mixbufpos = DSOUND_bufpos_to_mixpos(dsb->device, writepos);
418         /* Now mix the temporary buffer into the devices main buffer */
419         if ((writepos + len) <= dsb->device->buflen)
420                 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, len);
421         else
422         {
423                 DWORD todo = dsb->device->buflen - writepos;
424                 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, todo);
425                 dsb->device->mixfunction(ibuf + todo, dsb->device->mix_buffer, len - todo);
426         }
427
428         /* check for notification positions */
429         if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
430             dsb->state != STATE_STARTING) {
431                 INT ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
432                 DSOUND_CheckEvent(dsb, oldpos, ilen);
433         }
434
435         /* increase mix position */
436         dsb->primary_mixpos += len;
437         dsb->primary_mixpos %= dsb->device->buflen;
438
439         return len;
440 }
441
442 /**
443  * Mix some frames from the given secondary buffer "dsb" into the device
444  * primary buffer.
445  *
446  * dsb = the secondary buffer
447  * playpos = the current play position in the device buffer (primary buffer)
448  * writepos = the current safe-to-write position in the device buffer
449  * mixlen = the maximum number of bytes in the primary buffer to mix, from the
450  *          current writepos.
451  *
452  * Returns: the number of bytes beyond the writepos that were mixed.
453  */
454 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD mixlen)
455 {
456         /* The buffer's primary_mixpos may be before or after the device
457          * buffer's mixpos, but both must be ahead of writepos. */
458         DWORD primary_done;
459
460         TRACE("(%p,%d,%d)\n",dsb,writepos,mixlen);
461         TRACE("writepos=%d, primary_mixpos=%d, mixlen=%d\n", writepos, dsb->primary_mixpos, mixlen);
462         TRACE("looping=%d, leadin=%d\n", dsb->playflags, dsb->leadin);
463
464         /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
465         if (dsb->leadin && dsb->state == STATE_STARTING)
466         {
467                 if (mixlen > 2 * dsb->device->fraglen)
468                 {
469                         dsb->primary_mixpos += mixlen - 2 * dsb->device->fraglen;
470                         dsb->primary_mixpos %= dsb->device->buflen;
471                 }
472         }
473         dsb->leadin = FALSE;
474
475         /* calculate how much pre-buffering has already been done for this buffer */
476         primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
477
478         /* sanity */
479         if(mixlen < primary_done)
480         {
481                 /* Should *NEVER* happen */
482                 ERR("Fatal error. Under/Overflow? primary_done=%d, mixpos=%d/%d, primary_mixpos=%d, writepos=%d, mixlen=%d\n", primary_done,dsb->sec_mixpos, dsb->buflen, dsb->primary_mixpos, writepos, mixlen);
483                 dsb->primary_mixpos = writepos + mixlen;
484                 dsb->primary_mixpos %= dsb->device->buflen;
485                 return mixlen;
486         }
487
488         /* take into account already mixed data */
489         mixlen -= primary_done;
490
491         TRACE("primary_done=%d, mixlen (primary) = %i\n", primary_done, mixlen);
492
493         if (!mixlen)
494                 return primary_done;
495
496         /* First try to mix to the end of the buffer if possible
497          * Theoretically it would allow for better optimization
498         */
499         DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixlen);
500
501         /* re-calculate the primary done */
502         primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
503
504         TRACE("new primary_mixpos=%d, total mixed data=%d\n", dsb->primary_mixpos, primary_done);
505
506         /* Report back the total prebuffered amount for this buffer */
507         return primary_done;
508 }
509
510 /**
511  * For a DirectSoundDevice, go through all the currently playing buffers and
512  * mix them in to the device buffer.
513  *
514  * writepos = the current safe-to-write position in the primary buffer
515  * mixlen = the maximum amount to mix into the primary buffer
516  *          (beyond the current writepos)
517  * recover = true if the sound device may have been reset and the write
518  *           position in the device buffer changed
519  * all_stopped = reports back if all buffers have stopped
520  *
521  * Returns:  the length beyond the writepos that was mixed to.
522  */
523
524 static DWORD DSOUND_MixToPrimary(const DirectSoundDevice *device, DWORD writepos, DWORD mixlen, BOOL recover, BOOL *all_stopped)
525 {
526         INT i, len;
527         DWORD minlen = 0;
528         IDirectSoundBufferImpl  *dsb;
529
530         /* unless we find a running buffer, all have stopped */
531         *all_stopped = TRUE;
532
533         TRACE("(%d,%d,%d)\n", writepos, mixlen, recover);
534         for (i = 0; i < device->nrofbuffers; i++) {
535                 dsb = device->buffers[i];
536
537                 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
538
539                 if (dsb->buflen && dsb->state) {
540                         TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
541                         RtlAcquireResourceShared(&dsb->lock, TRUE);
542                         /* if buffer is stopping it is stopped now */
543                         if (dsb->state == STATE_STOPPING) {
544                                 dsb->state = STATE_STOPPED;
545                                 DSOUND_CheckEvent(dsb, 0, 0);
546                         } else if (dsb->state != STATE_STOPPED) {
547
548                                 /* if recovering, reset the mix position */
549                                 if ((dsb->state == STATE_STARTING) || recover) {
550                                         dsb->primary_mixpos = writepos;
551                                 }
552
553                                 /* if the buffer was starting, it must be playing now */
554                                 if (dsb->state == STATE_STARTING)
555                                         dsb->state = STATE_PLAYING;
556
557                                 /* mix next buffer into the main buffer */
558                                 len = DSOUND_MixOne(dsb, writepos, mixlen);
559
560                                 if (!minlen) minlen = len;
561
562                                 /* record the minimum length mixed from all buffers */
563                                 /* we only want to return the length which *all* buffers have mixed */
564                                 else if (len) minlen = (len < minlen) ? len : minlen;
565
566                                 *all_stopped = FALSE;
567                         }
568                         RtlReleaseResource(&dsb->lock);
569                 }
570         }
571
572         TRACE("Mixed at least %d from all buffers\n", minlen);
573         return minlen;
574 }
575
576 /**
577  * Add buffers to the emulated wave device system.
578  *
579  * device = The current dsound playback device
580  * force = If TRUE, the function will buffer up as many frags as possible,
581  *         even though and will ignore the actual state of the primary buffer.
582  *
583  * Returns:  None
584  */
585
586 static void DSOUND_WaveQueue(DirectSoundDevice *device, BOOL force)
587 {
588         DWORD prebuf_frames, buf_offs_bytes, wave_fragpos;
589         int prebuf_frags;
590         BYTE *buffer;
591         HRESULT hr;
592
593         TRACE("(%p)\n", device);
594
595         /* calculate the current wave frag position */
596         wave_fragpos = (device->pwplay + device->pwqueue) % device->helfrags;
597
598         /* calculate the current wave write position */
599         buf_offs_bytes = wave_fragpos * device->fraglen;
600
601         TRACE("wave_fragpos = %i, buf_offs_bytes = %i, pwqueue = %i, prebuf = %i\n",
602                 wave_fragpos, buf_offs_bytes, device->pwqueue, device->prebuf);
603
604         if (!force)
605         {
606                 /* check remaining prebuffered frags */
607                 prebuf_frags = device->mixpos / device->fraglen;
608                 if (prebuf_frags == device->helfrags)
609                         --prebuf_frags;
610                 TRACE("wave_fragpos = %d, mixpos_frags = %d\n", wave_fragpos, prebuf_frags);
611                 if (prebuf_frags < wave_fragpos)
612                         prebuf_frags += device->helfrags;
613                 prebuf_frags -= wave_fragpos;
614                 TRACE("wanted prebuf_frags = %d\n", prebuf_frags);
615         }
616         else
617                 /* buffer the maximum amount of frags */
618                 prebuf_frags = device->prebuf;
619
620         /* limit to the queue we have left */
621         if ((prebuf_frags + device->pwqueue) > device->prebuf)
622                 prebuf_frags = device->prebuf - device->pwqueue;
623
624         TRACE("prebuf_frags = %i\n", prebuf_frags);
625
626         if(!prebuf_frags)
627                 return;
628
629         /* adjust queue */
630         device->pwqueue += prebuf_frags;
631
632         prebuf_frames = ((prebuf_frags + wave_fragpos > device->helfrags) ?
633                         (device->helfrags - wave_fragpos) :
634                         (prebuf_frags)) * device->fraglen / device->pwfx->nBlockAlign;
635
636         hr = IAudioRenderClient_GetBuffer(device->render, prebuf_frames, &buffer);
637         if(FAILED(hr)){
638                 WARN("GetBuffer failed: %08x\n", hr);
639                 return;
640         }
641
642         memcpy(buffer, device->buffer + buf_offs_bytes,
643                         prebuf_frames * device->pwfx->nBlockAlign);
644
645         hr = IAudioRenderClient_ReleaseBuffer(device->render, prebuf_frames, 0);
646         if(FAILED(hr)){
647                 WARN("ReleaseBuffer failed: %08x\n", hr);
648                 return;
649         }
650
651         /* check if anything wrapped */
652         prebuf_frags = prebuf_frags + wave_fragpos - device->helfrags;
653         if(prebuf_frags > 0){
654                 prebuf_frames = prebuf_frags * device->fraglen / device->pwfx->nBlockAlign;
655
656                 hr = IAudioRenderClient_GetBuffer(device->render, prebuf_frames, &buffer);
657                 if(FAILED(hr)){
658                         WARN("GetBuffer failed: %08x\n", hr);
659                         return;
660                 }
661
662                 memcpy(buffer, device->buffer, prebuf_frames * device->pwfx->nBlockAlign);
663
664                 hr = IAudioRenderClient_ReleaseBuffer(device->render, prebuf_frames, 0);
665                 if(FAILED(hr)){
666                         WARN("ReleaseBuffer failed: %08x\n", hr);
667                         return;
668                 }
669         }
670
671         TRACE("queue now = %i\n", device->pwqueue);
672 }
673
674 /**
675  * Perform mixing for a Direct Sound device. That is, go through all the
676  * secondary buffers (the sound bites currently playing) and mix them in
677  * to the primary buffer (the device buffer).
678  */
679 static void DSOUND_PerformMix(DirectSoundDevice *device)
680 {
681         UINT64 clock_pos, clock_freq, pos_bytes;
682         UINT delta_frags;
683         HRESULT hr;
684
685         TRACE("(%p)\n", device);
686
687         /* **** */
688         EnterCriticalSection(&device->mixlock);
689
690         hr = IAudioClock_GetFrequency(device->clock, &clock_freq);
691         if(FAILED(hr)){
692                 WARN("GetFrequency failed: %08x\n", hr);
693         LeaveCriticalSection(&device->mixlock);
694                 return;
695         }
696
697         hr = IAudioClock_GetPosition(device->clock, &clock_pos, NULL);
698         if(FAILED(hr)){
699                 WARN("GetCurrentPadding failed: %08x\n", hr);
700         LeaveCriticalSection(&device->mixlock);
701                 return;
702         }
703
704         pos_bytes = (clock_pos * device->pwfx->nSamplesPerSec * device->pwfx->nBlockAlign) / clock_freq;
705
706         delta_frags = (pos_bytes - device->last_pos_bytes) / device->fraglen;
707         if(delta_frags > 0){
708                 device->pwplay += delta_frags;
709                 device->pwplay %= device->helfrags;
710                 device->pwqueue -= delta_frags;
711                 device->last_pos_bytes = pos_bytes - (pos_bytes % device->fraglen);
712         }
713
714         if (device->priolevel != DSSCL_WRITEPRIMARY) {
715                 BOOL recover = FALSE, all_stopped = FALSE;
716                 DWORD playpos, writepos, writelead, maxq, frag, prebuff_max, prebuff_left, size1, size2, mixplaypos, mixplaypos2;
717                 LPVOID buf1, buf2;
718                 int nfiller;
719
720                 /* the sound of silence */
721                 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
722
723                 /* get the position in the primary buffer */
724                 if (DSOUND_PrimaryGetPosition(device, &playpos, &writepos) != 0){
725                         LeaveCriticalSection(&(device->mixlock));
726                         return;
727                 }
728
729                 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
730                         playpos,writepos,device->playpos,device->mixpos,device->buflen);
731                 assert(device->playpos < device->buflen);
732
733                 mixplaypos = DSOUND_bufpos_to_mixpos(device, device->playpos);
734                 mixplaypos2 = DSOUND_bufpos_to_mixpos(device, playpos);
735
736                 /* calc maximum prebuff */
737                 prebuff_max = (device->prebuf * device->fraglen);
738                 if (playpos + prebuff_max >= device->helfrags * device->fraglen)
739                         prebuff_max += device->buflen - device->helfrags * device->fraglen;
740
741                 /* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
742                 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
743                 writelead = DSOUND_BufPtrDiff(device->buflen, writepos, playpos);
744
745                 /* check for underrun. underrun occurs when the write position passes the mix position
746                  * also wipe out just-played sound data */
747                 if((prebuff_left > prebuff_max) || (device->state == STATE_STOPPED) || (device->state == STATE_STARTING)){
748                         if (device->state == STATE_STOPPING || device->state == STATE_PLAYING)
749                                 WARN("Probable buffer underrun\n");
750                         else TRACE("Buffer starting or buffer underrun\n");
751
752                         /* recover mixing for all buffers */
753                         recover = TRUE;
754
755                         /* reset mix position to write position */
756                         device->mixpos = writepos;
757
758                         ZeroMemory(device->mix_buffer, device->mix_buffer_len);
759                         ZeroMemory(device->buffer, device->buflen);
760                 } else if (playpos < device->playpos) {
761                         buf1 = device->buffer + device->playpos;
762                         buf2 = device->buffer;
763                         size1 = device->buflen - device->playpos;
764                         size2 = playpos;
765                         FillMemory(device->mix_buffer + mixplaypos, device->mix_buffer_len - mixplaypos, 0);
766                         FillMemory(device->mix_buffer, mixplaypos2, 0);
767                         FillMemory(buf1, size1, nfiller);
768                         if (playpos && (!buf2 || !size2))
769                                 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__, device->playpos, device->mixpos, playpos, writepos);
770                         FillMemory(buf2, size2, nfiller);
771                 } else {
772                         buf1 = device->buffer + device->playpos;
773                         buf2 = NULL;
774                         size1 = playpos - device->playpos;
775                         size2 = 0;
776                         FillMemory(device->mix_buffer + mixplaypos, mixplaypos2 - mixplaypos, 0);
777                         FillMemory(buf1, size1, nfiller);
778                 }
779                 device->playpos = playpos;
780
781                 /* find the maximum we can prebuffer from current write position */
782                 maxq = (writelead < prebuff_max) ? (prebuff_max - writelead) : 0;
783
784                 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
785                         prebuff_left, device->prebuf, device->fraglen, prebuff_max, writelead);
786
787                 /* do the mixing */
788                 frag = DSOUND_MixToPrimary(device, writepos, maxq, recover, &all_stopped);
789
790                 if (frag + writepos > device->buflen)
791                 {
792                         DWORD todo = device->buflen - writepos;
793                         device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, todo);
794                         device->normfunction(device->mix_buffer, device->buffer, frag - todo);
795                 }
796                 else
797                         device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, frag);
798
799                 /* update the mix position, taking wrap-around into account */
800                 device->mixpos = writepos + frag;
801                 device->mixpos %= device->buflen;
802
803                 /* update prebuff left */
804                 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
805
806                 /* check if have a whole fragment */
807                 if (prebuff_left >= device->fraglen){
808
809                         /* update the wave queue */
810                         DSOUND_WaveQueue(device, FALSE);
811
812                         /* buffers are full. start playing if applicable */
813                         if(device->state == STATE_STARTING){
814                                 TRACE("started primary buffer\n");
815                                 if(DSOUND_PrimaryPlay(device) != DS_OK){
816                                         WARN("DSOUND_PrimaryPlay failed\n");
817                                 }
818                                 else{
819                                         /* we are playing now */
820                                         device->state = STATE_PLAYING;
821                                 }
822                         }
823
824                         /* buffers are full. start stopping if applicable */
825                         if(device->state == STATE_STOPPED){
826                                 TRACE("restarting primary buffer\n");
827                                 if(DSOUND_PrimaryPlay(device) != DS_OK){
828                                         WARN("DSOUND_PrimaryPlay failed\n");
829                                 }
830                                 else{
831                                         /* start stopping again. as soon as there is no more data, it will stop */
832                                         device->state = STATE_STOPPING;
833                                 }
834                         }
835                 }
836
837                 /* if device was stopping, its for sure stopped when all buffers have stopped */
838                 else if((all_stopped == TRUE) && (device->state == STATE_STOPPING)){
839                         TRACE("All buffers have stopped. Stopping primary buffer\n");
840                         device->state = STATE_STOPPED;
841
842                         /* stop the primary buffer now */
843                         DSOUND_PrimaryStop(device);
844                 }
845
846         } else {
847
848                 DSOUND_WaveQueue(device, TRUE);
849
850                 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
851                 if (device->state == STATE_STARTING) {
852                         if (DSOUND_PrimaryPlay(device) != DS_OK)
853                                 WARN("DSOUND_PrimaryPlay failed\n");
854                         else
855                                 device->state = STATE_PLAYING;
856                 }
857                 else if (device->state == STATE_STOPPING) {
858                         if (DSOUND_PrimaryStop(device) != DS_OK)
859                                 WARN("DSOUND_PrimaryStop failed\n");
860                         else
861                                 device->state = STATE_STOPPED;
862                 }
863         }
864
865         LeaveCriticalSection(&(device->mixlock));
866         /* **** */
867 }
868
869 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD_PTR dwUser,
870                            DWORD_PTR dw1, DWORD_PTR dw2)
871 {
872         DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
873         DWORD start_time =  GetTickCount();
874         DWORD end_time;
875         TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
876         TRACE("entering at %d\n", start_time);
877
878         RtlAcquireResourceShared(&(device->buffer_list_lock), TRUE);
879
880         if (device->ref)
881                 DSOUND_PerformMix(device);
882
883         RtlReleaseResource(&(device->buffer_list_lock));
884
885         end_time = GetTickCount();
886         TRACE("completed processing at %d, duration = %d\n", end_time, end_time - start_time);
887 }