dsound: Added a windowed-sinc resampler.
[wine/multimedia.git] / dlls / dsound / mixer.c
blobec5a264f0d63cb21521e61b0e42c6ae15754a3ad
1 /* DirectSound
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
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.
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.
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
25 #include <assert.h>
26 #include <stdarg.h>
27 #include <math.h> /* Insomnia - pow() function */
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 #include "fir.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
47 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
49 double temp;
50 TRACE("(%p)\n",volpan);
52 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
53 /* the AmpFactors are expressed in 16.16 fixed point */
54 volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
55 /* FIXME: dwPan{Left|Right}AmpFactor */
57 /* FIXME: use calculated vol and pan ampfactors */
58 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
59 volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
60 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
61 volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
63 TRACE("left = %x, right = %x\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
66 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
68 double left,right;
69 TRACE("(%p)\n",volpan);
71 TRACE("left=%x, right=%x\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
72 if (volpan->dwTotalLeftAmpFactor==0)
73 left=-10000;
74 else
75 left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
76 if (volpan->dwTotalRightAmpFactor==0)
77 right=-10000;
78 else
79 right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
80 if (left<right)
82 volpan->lVolume=right;
83 volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
85 else
87 volpan->lVolume=left;
88 volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
90 if (volpan->lVolume < -10000)
91 volpan->lVolume=-10000;
92 volpan->lPan=right-left;
93 if (volpan->lPan < -10000)
94 volpan->lPan=-10000;
96 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
99 /** Convert a primary buffer position to a pointer position for device->mix_buffer
100 * device: DirectSoundDevice for which to calculate
101 * pos: Primary buffer position to converts
102 * Returns: Offset for mix_buffer
104 DWORD DSOUND_bufpos_to_mixpos(const DirectSoundDevice* device, DWORD pos)
106 DWORD ret = pos * 32 / device->pwfx->wBitsPerSample;
107 if (device->pwfx->wBitsPerSample == 32)
108 ret *= 2;
109 return ret;
113 * Recalculate the size for temporary buffer, and new writelead
114 * Should be called when one of the following things occur:
115 * - Primary buffer format is changed
116 * - This buffer format (frequency) is changed
118 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
120 DWORD ichannels = dsb->pwfx->nChannels;
121 DWORD ochannels = dsb->device->pwfx->nChannels;
122 WAVEFORMATEXTENSIBLE *pwfxe;
123 BOOL ieee = FALSE;
125 TRACE("(%p)\n",dsb);
127 pwfxe = (WAVEFORMATEXTENSIBLE *) dsb->pwfx;
129 if ((pwfxe->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) || ((pwfxe->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
130 && (IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))))
131 ieee = TRUE;
134 * Recalculate FIR step and gain.
136 * firstep says how many points of the FIR exist per one
137 * sample in the secondary buffer. firgain specifies what
138 * to multiply the FIR output by in order to attenuate it correctly.
140 if (dsb->freqAdjust > 1.0f) {
142 * Yes, round it a bit to make sure that the
143 * linear interpolation factor never changes.
145 dsb->firstep = ceil(fir_step / dsb->freqAdjust);
146 } else {
147 dsb->firstep = fir_step;
149 dsb->firgain = (float)dsb->firstep / fir_step;
151 /* calculate the 10ms write lead */
152 dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
154 dsb->freqAcc = 0;
156 dsb->get_aux = ieee ? getbpp[4] : getbpp[dsb->pwfx->wBitsPerSample/8 - 1];
157 dsb->put_aux = putbpp[dsb->device->pwfx->wBitsPerSample/8 - 1];
159 dsb->get = dsb->get_aux;
160 dsb->put = dsb->put_aux;
162 if (ichannels == ochannels)
164 dsb->mix_channels = ichannels;
165 if (ichannels > 32) {
166 FIXME("Copying %u channels is unsupported, limiting to first 32\n", ichannels);
167 dsb->mix_channels = 32;
170 else if (ichannels == 1)
172 dsb->mix_channels = 1;
173 dsb->put = put_mono2stereo;
175 else if (ochannels == 1)
177 dsb->mix_channels = 1;
178 dsb->get = get_mono;
180 else
182 if (ichannels > 2)
183 FIXME("Conversion from %u to %u channels is not implemented, falling back to stereo\n", ichannels, ochannels);
184 dsb->mix_channels = 2;
189 * Check for application callback requests for when the play position
190 * reaches certain points.
192 * The offsets that will be triggered will be those between the recorded
193 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
194 * beyond that position.
196 void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
198 int i;
199 DWORD offset;
200 LPDSBPOSITIONNOTIFY event;
201 TRACE("(%p,%d)\n",dsb,len);
203 if (dsb->nrofnotifies == 0)
204 return;
206 TRACE("(%p) buflen = %d, playpos = %d, len = %d\n",
207 dsb, dsb->buflen, playpos, len);
208 for (i = 0; i < dsb->nrofnotifies ; i++) {
209 event = dsb->notifies + i;
210 offset = event->dwOffset;
211 TRACE("checking %d, position %d, event = %p\n",
212 i, offset, event->hEventNotify);
213 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
214 /* OK. [Inside DirectX, p274] */
215 /* Windows does not seem to enforce this, and some apps rely */
216 /* on that, so we can't stop there. */
217 /* */
218 /* This also means we can't sort the entries by offset, */
219 /* because DSBPN_OFFSETSTOP == -1 */
220 if (offset == DSBPN_OFFSETSTOP) {
221 if (dsb->state == STATE_STOPPED) {
222 SetEvent(event->hEventNotify);
223 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
225 continue;
227 if ((playpos + len) >= dsb->buflen) {
228 if ((offset < ((playpos + len) % dsb->buflen)) ||
229 (offset >= playpos)) {
230 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
231 SetEvent(event->hEventNotify);
233 } else {
234 if ((offset >= playpos) && (offset < (playpos + len))) {
235 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
236 SetEvent(event->hEventNotify);
242 static inline float get_current_sample(const IDirectSoundBufferImpl *dsb,
243 DWORD mixpos, DWORD channel)
245 if (mixpos >= dsb->buflen && !(dsb->playflags & DSBPLAY_LOOPING))
246 return 0.0f;
247 return dsb->get(dsb, mixpos % dsb->buflen, channel);
250 static UINT cp_fields_noresample(IDirectSoundBufferImpl *dsb,
251 UINT ostride, UINT count)
253 UINT istride = dsb->pwfx->nBlockAlign;
254 DWORD channel, i;
255 for (i = 0; i < count; i++)
256 for (channel = 0; channel < dsb->mix_channels; channel++)
257 dsb->put(dsb, i * ostride, channel, get_current_sample(dsb,
258 dsb->sec_mixpos + i * istride, channel));
259 return count;
262 static UINT cp_fields_resample(IDirectSoundBufferImpl *dsb,
263 UINT ostride, UINT count, float *freqAcc)
265 UINT i, channel;
266 UINT istride = dsb->pwfx->nBlockAlign;
268 float freqAdjust = dsb->freqAdjust;
269 float freqAcc_start = *freqAcc;
270 float freqAcc_end = freqAcc_start + count * freqAdjust;
271 UINT dsbfirstep = dsb->firstep;
272 UINT channels = dsb->mix_channels;
273 UINT max_ipos = freqAcc_start + count * freqAdjust;
275 UINT fir_cachesize = (fir_len + dsbfirstep - 2) / dsbfirstep;
276 UINT required_input = max_ipos + fir_cachesize;
278 float* intermediate = HeapAlloc(GetProcessHeap(), 0,
279 sizeof(float) * required_input * channels);
281 float* fir_copy = HeapAlloc(GetProcessHeap(), 0,
282 sizeof(float) * fir_cachesize);
284 /* Important: this buffer MUST be non-interleaved
285 * if you want -msse3 to have any effect.
286 * This is good for CPU cache effects, too.
288 float* itmp = intermediate;
289 for (channel = 0; channel < channels; channel++)
290 for (i = 0; i < required_input; i++)
291 *(itmp++) = get_current_sample(dsb,
292 dsb->sec_mixpos + i * istride, channel);
294 for(i = 0; i < count; ++i) {
295 float total_fir_steps = (freqAcc_start + i * freqAdjust) * dsbfirstep;
296 UINT int_fir_steps = total_fir_steps;
297 UINT ipos = int_fir_steps / dsbfirstep;
299 UINT idx = (ipos + 1) * dsbfirstep - int_fir_steps - 1;
300 float rem = int_fir_steps + 1.0 - total_fir_steps;
302 int fir_used = 0;
303 while (idx < fir_len - 1) {
304 fir_copy[fir_used++] = fir[idx] * (1.0 - rem) + fir[idx + 1] * rem;
305 idx += dsb->firstep;
308 assert(fir_used <= fir_cachesize);
309 assert(ipos + fir_used <= required_input);
311 for (channel = 0; channel < dsb->mix_channels; channel++) {
312 int j;
313 float sum = 0.0;
314 float* cache = &intermediate[channel * required_input + ipos];
315 for (j = 0; j < fir_used; j++)
316 sum += fir_copy[j] * cache[j];
317 dsb->put(dsb, i * ostride, channel, sum * dsb->firgain);
321 freqAcc_end -= (int)freqAcc_end;
322 *freqAcc = freqAcc_end;
324 HeapFree(GetProcessHeap(), 0, fir_copy);
325 HeapFree(GetProcessHeap(), 0, intermediate);
327 return max_ipos;
330 static void cp_fields(IDirectSoundBufferImpl *dsb,
331 UINT ostride, UINT count, float *freqAcc)
333 DWORD ipos, adv;
335 if (dsb->freqAdjust == 1.0)
336 adv = cp_fields_noresample(dsb, ostride, count); /* *freqAcc is unmodified */
337 else
338 adv = cp_fields_resample(dsb, ostride, count, freqAcc);
340 ipos = dsb->sec_mixpos + adv * dsb->pwfx->nBlockAlign;
341 if (ipos >= dsb->buflen) {
342 if (dsb->playflags & DSBPLAY_LOOPING)
343 ipos %= dsb->buflen;
344 else {
345 ipos = 0;
346 dsb->state = STATE_STOPPED;
350 dsb->sec_mixpos = ipos;
354 * Calculate the distance between two buffer offsets, taking wraparound
355 * into account.
357 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
359 /* If these asserts fail, the problem is not here, but in the underlying code */
360 assert(ptr1 < buflen);
361 assert(ptr2 < buflen);
362 if (ptr1 >= ptr2) {
363 return ptr1 - ptr2;
364 } else {
365 return buflen + ptr1 - ptr2;
369 * Mix at most the given amount of data into the allocated temporary buffer
370 * of the given secondary buffer, starting from the dsb's first currently
371 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
372 * and bits-per-sample so that it is ideal for the primary buffer.
373 * Doesn't perform any mixing - this is a straight copy/convert operation.
375 * dsb = the secondary buffer
376 * writepos = Starting position of changed buffer
377 * len = number of bytes to resample from writepos
379 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
381 static void DSOUND_MixToTemporary(IDirectSoundBufferImpl *dsb, DWORD tmp_len)
383 INT oAdvance = dsb->device->pwfx->nBlockAlign;
384 INT size = tmp_len / oAdvance;
386 if (dsb->device->tmp_buffer_len < tmp_len || !dsb->device->tmp_buffer)
388 dsb->device->tmp_buffer_len = tmp_len;
389 if (dsb->device->tmp_buffer)
390 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, tmp_len);
391 else
392 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, tmp_len);
395 cp_fields(dsb, oAdvance, size, &dsb->freqAcc);
398 /** Apply volume to the given soundbuffer from (primary) position writepos and length len
399 * Returns: NULL if no volume needs to be applied
400 * or else a memory handle that holds 'len' volume adjusted buffer */
401 static LPBYTE DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT len)
403 INT i;
404 BYTE *bpc;
405 INT16 *bps, *mems;
406 DWORD vLeft, vRight;
407 INT nChannels = dsb->device->pwfx->nChannels;
408 LPBYTE mem = dsb->device->tmp_buffer;
410 TRACE("(%p,%d)\n",dsb,len);
411 TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalLeftAmpFactor,
412 dsb->volpan.dwTotalRightAmpFactor);
414 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
415 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
416 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
417 return NULL; /* Nothing to do */
419 if (nChannels != 1 && nChannels != 2)
421 FIXME("There is no support for %d channels\n", nChannels);
422 return NULL;
425 if (dsb->device->pwfx->wBitsPerSample != 8 && dsb->device->pwfx->wBitsPerSample != 16)
427 FIXME("There is no support for %d bpp\n", dsb->device->pwfx->wBitsPerSample);
428 return NULL;
431 assert(dsb->device->tmp_buffer_len >= len && dsb->device->tmp_buffer);
433 bpc = dsb->device->tmp_buffer;
434 bps = (INT16 *)bpc;
435 mems = (INT16 *)mem;
436 vLeft = dsb->volpan.dwTotalLeftAmpFactor;
437 if (nChannels > 1)
438 vRight = dsb->volpan.dwTotalRightAmpFactor;
439 else
440 vRight = vLeft;
442 switch (dsb->device->pwfx->wBitsPerSample) {
443 case 8:
444 /* 8-bit WAV is unsigned, but we need to operate */
445 /* on signed data for this to work properly */
446 for (i = 0; i < len-1; i+=2) {
447 *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
448 *(bpc++) = (((*(mem++) - 128) * vRight) >> 16) + 128;
450 if (len % 2 == 1 && nChannels == 1)
451 *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
452 break;
453 case 16:
454 /* 16-bit WAV is signed -- much better */
455 for (i = 0; i < len-3; i += 4) {
456 *(bps++) = (*(mems++) * vLeft) >> 16;
457 *(bps++) = (*(mems++) * vRight) >> 16;
459 if (len % 4 == 2 && nChannels == 1)
460 *(bps++) = ((INT)*(mems++) * vLeft) >> 16;
461 break;
463 return dsb->device->tmp_buffer;
467 * Mix (at most) the given number of bytes into the given position of the
468 * device buffer, from the secondary buffer "dsb" (starting at the current
469 * mix position for that buffer).
471 * Returns the number of bytes actually mixed into the device buffer. This
472 * will match fraglen unless the end of the secondary buffer is reached
473 * (and it is not looping).
475 * dsb = the secondary buffer to mix from
476 * writepos = position (offset) in device buffer to write at
477 * fraglen = number of bytes to mix
479 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
481 INT len = fraglen;
482 BYTE *ibuf, *volbuf;
483 DWORD oldpos, mixbufpos;
485 TRACE("sec_mixpos=%d/%d\n", dsb->sec_mixpos, dsb->buflen);
486 TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
488 if (len % dsb->device->pwfx->nBlockAlign) {
489 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
490 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
491 len -= len % nBlockAlign; /* data alignment */
494 /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
495 oldpos = dsb->sec_mixpos;
497 DSOUND_MixToTemporary(dsb, len);
498 ibuf = dsb->device->tmp_buffer;
500 /* Apply volume if needed */
501 volbuf = DSOUND_MixerVol(dsb, len);
502 if (volbuf)
503 ibuf = volbuf;
505 mixbufpos = DSOUND_bufpos_to_mixpos(dsb->device, writepos);
506 /* Now mix the temporary buffer into the devices main buffer */
507 if ((writepos + len) <= dsb->device->buflen)
508 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, len);
509 else
511 DWORD todo = dsb->device->buflen - writepos;
512 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, todo);
513 dsb->device->mixfunction(ibuf + todo, dsb->device->mix_buffer, len - todo);
516 /* check for notification positions */
517 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
518 dsb->state != STATE_STARTING) {
519 INT ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
520 DSOUND_CheckEvent(dsb, oldpos, ilen);
523 /* increase mix position */
524 dsb->primary_mixpos += len;
525 dsb->primary_mixpos %= dsb->device->buflen;
527 return len;
531 * Mix some frames from the given secondary buffer "dsb" into the device
532 * primary buffer.
534 * dsb = the secondary buffer
535 * playpos = the current play position in the device buffer (primary buffer)
536 * writepos = the current safe-to-write position in the device buffer
537 * mixlen = the maximum number of bytes in the primary buffer to mix, from the
538 * current writepos.
540 * Returns: the number of bytes beyond the writepos that were mixed.
542 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD mixlen)
544 /* The buffer's primary_mixpos may be before or after the device
545 * buffer's mixpos, but both must be ahead of writepos. */
546 DWORD primary_done;
548 TRACE("(%p,%d,%d)\n",dsb,writepos,mixlen);
549 TRACE("writepos=%d, primary_mixpos=%d, mixlen=%d\n", writepos, dsb->primary_mixpos, mixlen);
550 TRACE("looping=%d, leadin=%d\n", dsb->playflags, dsb->leadin);
552 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
553 if (dsb->leadin && dsb->state == STATE_STARTING)
555 if (mixlen > 2 * dsb->device->fraglen)
557 dsb->primary_mixpos += mixlen - 2 * dsb->device->fraglen;
558 dsb->primary_mixpos %= dsb->device->buflen;
561 dsb->leadin = FALSE;
563 /* calculate how much pre-buffering has already been done for this buffer */
564 primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
566 /* sanity */
567 if(mixlen < primary_done)
569 /* Should *NEVER* happen */
570 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);
571 dsb->primary_mixpos = writepos + mixlen;
572 dsb->primary_mixpos %= dsb->device->buflen;
573 return mixlen;
576 /* take into account already mixed data */
577 mixlen -= primary_done;
579 TRACE("primary_done=%d, mixlen (primary) = %i\n", primary_done, mixlen);
581 if (!mixlen)
582 return primary_done;
584 /* First try to mix to the end of the buffer if possible
585 * Theoretically it would allow for better optimization
587 DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixlen);
589 /* re-calculate the primary done */
590 primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
592 TRACE("new primary_mixpos=%d, total mixed data=%d\n", dsb->primary_mixpos, primary_done);
594 /* Report back the total prebuffered amount for this buffer */
595 return primary_done;
599 * For a DirectSoundDevice, go through all the currently playing buffers and
600 * mix them in to the device buffer.
602 * writepos = the current safe-to-write position in the primary buffer
603 * mixlen = the maximum amount to mix into the primary buffer
604 * (beyond the current writepos)
605 * recover = true if the sound device may have been reset and the write
606 * position in the device buffer changed
607 * all_stopped = reports back if all buffers have stopped
609 * Returns: the length beyond the writepos that was mixed to.
612 static DWORD DSOUND_MixToPrimary(const DirectSoundDevice *device, DWORD writepos, DWORD mixlen, BOOL recover, BOOL *all_stopped)
614 INT i, len;
615 DWORD minlen = 0;
616 IDirectSoundBufferImpl *dsb;
618 /* unless we find a running buffer, all have stopped */
619 *all_stopped = TRUE;
621 TRACE("(%d,%d,%d)\n", writepos, mixlen, recover);
622 for (i = 0; i < device->nrofbuffers; i++) {
623 dsb = device->buffers[i];
625 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
627 if (dsb->buflen && dsb->state) {
628 TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
629 RtlAcquireResourceShared(&dsb->lock, TRUE);
630 /* if buffer is stopping it is stopped now */
631 if (dsb->state == STATE_STOPPING) {
632 dsb->state = STATE_STOPPED;
633 DSOUND_CheckEvent(dsb, 0, 0);
634 } else if (dsb->state != STATE_STOPPED) {
636 /* if recovering, reset the mix position */
637 if ((dsb->state == STATE_STARTING) || recover) {
638 dsb->primary_mixpos = writepos;
641 /* if the buffer was starting, it must be playing now */
642 if (dsb->state == STATE_STARTING)
643 dsb->state = STATE_PLAYING;
645 /* mix next buffer into the main buffer */
646 len = DSOUND_MixOne(dsb, writepos, mixlen);
648 if (!minlen) minlen = len;
650 /* record the minimum length mixed from all buffers */
651 /* we only want to return the length which *all* buffers have mixed */
652 else if (len) minlen = (len < minlen) ? len : minlen;
654 *all_stopped = FALSE;
656 RtlReleaseResource(&dsb->lock);
660 TRACE("Mixed at least %d from all buffers\n", minlen);
661 return minlen;
665 * Add buffers to the emulated wave device system.
667 * device = The current dsound playback device
668 * force = If TRUE, the function will buffer up as many frags as possible,
669 * even though and will ignore the actual state of the primary buffer.
671 * Returns: None
674 static void DSOUND_WaveQueue(DirectSoundDevice *device, BOOL force)
676 DWORD prebuf_frames, buf_offs_bytes, wave_fragpos;
677 int prebuf_frags;
678 BYTE *buffer;
679 HRESULT hr;
681 TRACE("(%p)\n", device);
683 /* calculate the current wave frag position */
684 wave_fragpos = (device->pwplay + device->pwqueue) % device->helfrags;
686 /* calculate the current wave write position */
687 buf_offs_bytes = wave_fragpos * device->fraglen;
689 TRACE("wave_fragpos = %i, buf_offs_bytes = %i, pwqueue = %i, prebuf = %i\n",
690 wave_fragpos, buf_offs_bytes, device->pwqueue, device->prebuf);
692 if (!force)
694 /* check remaining prebuffered frags */
695 prebuf_frags = device->mixpos / device->fraglen;
696 if (prebuf_frags == device->helfrags)
697 --prebuf_frags;
698 TRACE("wave_fragpos = %d, mixpos_frags = %d\n", wave_fragpos, prebuf_frags);
699 if (prebuf_frags < wave_fragpos)
700 prebuf_frags += device->helfrags;
701 prebuf_frags -= wave_fragpos;
702 TRACE("wanted prebuf_frags = %d\n", prebuf_frags);
704 else
705 /* buffer the maximum amount of frags */
706 prebuf_frags = device->prebuf;
708 /* limit to the queue we have left */
709 if ((prebuf_frags + device->pwqueue) > device->prebuf)
710 prebuf_frags = device->prebuf - device->pwqueue;
712 TRACE("prebuf_frags = %i\n", prebuf_frags);
714 if(!prebuf_frags)
715 return;
717 /* adjust queue */
718 device->pwqueue += prebuf_frags;
720 prebuf_frames = ((prebuf_frags + wave_fragpos > device->helfrags) ?
721 (device->helfrags - wave_fragpos) :
722 (prebuf_frags)) * device->fraglen / device->pwfx->nBlockAlign;
724 hr = IAudioRenderClient_GetBuffer(device->render, prebuf_frames, &buffer);
725 if(FAILED(hr)){
726 WARN("GetBuffer failed: %08x\n", hr);
727 return;
730 memcpy(buffer, device->buffer + buf_offs_bytes,
731 prebuf_frames * device->pwfx->nBlockAlign);
733 hr = IAudioRenderClient_ReleaseBuffer(device->render, prebuf_frames, 0);
734 if(FAILED(hr)){
735 WARN("ReleaseBuffer failed: %08x\n", hr);
736 return;
739 /* check if anything wrapped */
740 prebuf_frags = prebuf_frags + wave_fragpos - device->helfrags;
741 if(prebuf_frags > 0){
742 prebuf_frames = prebuf_frags * device->fraglen / device->pwfx->nBlockAlign;
744 hr = IAudioRenderClient_GetBuffer(device->render, prebuf_frames, &buffer);
745 if(FAILED(hr)){
746 WARN("GetBuffer failed: %08x\n", hr);
747 return;
750 memcpy(buffer, device->buffer, prebuf_frames * device->pwfx->nBlockAlign);
752 hr = IAudioRenderClient_ReleaseBuffer(device->render, prebuf_frames, 0);
753 if(FAILED(hr)){
754 WARN("ReleaseBuffer failed: %08x\n", hr);
755 return;
759 TRACE("queue now = %i\n", device->pwqueue);
763 * Perform mixing for a Direct Sound device. That is, go through all the
764 * secondary buffers (the sound bites currently playing) and mix them in
765 * to the primary buffer (the device buffer).
767 static void DSOUND_PerformMix(DirectSoundDevice *device)
769 UINT64 clock_pos, clock_freq, pos_bytes;
770 UINT delta_frags;
771 HRESULT hr;
773 TRACE("(%p)\n", device);
775 /* **** */
776 EnterCriticalSection(&device->mixlock);
778 hr = IAudioClock_GetFrequency(device->clock, &clock_freq);
779 if(FAILED(hr)){
780 WARN("GetFrequency failed: %08x\n", hr);
781 LeaveCriticalSection(&device->mixlock);
782 return;
785 hr = IAudioClock_GetPosition(device->clock, &clock_pos, NULL);
786 if(FAILED(hr)){
787 WARN("GetCurrentPadding failed: %08x\n", hr);
788 LeaveCriticalSection(&device->mixlock);
789 return;
792 pos_bytes = (clock_pos * device->pwfx->nSamplesPerSec * device->pwfx->nBlockAlign) / clock_freq;
794 delta_frags = (pos_bytes - device->last_pos_bytes) / device->fraglen;
795 if(delta_frags > 0){
796 device->pwplay += delta_frags;
797 device->pwplay %= device->helfrags;
798 device->pwqueue -= delta_frags;
799 device->last_pos_bytes = pos_bytes - (pos_bytes % device->fraglen);
802 if (device->priolevel != DSSCL_WRITEPRIMARY) {
803 BOOL recover = FALSE, all_stopped = FALSE;
804 DWORD playpos, writepos, writelead, maxq, frag, prebuff_max, prebuff_left, size1, size2, mixplaypos, mixplaypos2;
805 LPVOID buf1, buf2;
806 int nfiller;
808 /* the sound of silence */
809 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
811 /* get the position in the primary buffer */
812 if (DSOUND_PrimaryGetPosition(device, &playpos, &writepos) != 0){
813 LeaveCriticalSection(&(device->mixlock));
814 return;
817 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
818 playpos,writepos,device->playpos,device->mixpos,device->buflen);
819 assert(device->playpos < device->buflen);
821 mixplaypos = DSOUND_bufpos_to_mixpos(device, device->playpos);
822 mixplaypos2 = DSOUND_bufpos_to_mixpos(device, playpos);
824 /* calc maximum prebuff */
825 prebuff_max = (device->prebuf * device->fraglen);
826 if (playpos + prebuff_max >= device->helfrags * device->fraglen)
827 prebuff_max += device->buflen - device->helfrags * device->fraglen;
829 /* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
830 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
831 writelead = DSOUND_BufPtrDiff(device->buflen, writepos, playpos);
833 /* check for underrun. underrun occurs when the write position passes the mix position
834 * also wipe out just-played sound data */
835 if((prebuff_left > prebuff_max) || (device->state == STATE_STOPPED) || (device->state == STATE_STARTING)){
836 if (device->state == STATE_STOPPING || device->state == STATE_PLAYING)
837 WARN("Probable buffer underrun\n");
838 else TRACE("Buffer starting or buffer underrun\n");
840 /* recover mixing for all buffers */
841 recover = TRUE;
843 /* reset mix position to write position */
844 device->mixpos = writepos;
846 ZeroMemory(device->mix_buffer, device->mix_buffer_len);
847 ZeroMemory(device->buffer, device->buflen);
848 } else if (playpos < device->playpos) {
849 buf1 = device->buffer + device->playpos;
850 buf2 = device->buffer;
851 size1 = device->buflen - device->playpos;
852 size2 = playpos;
853 FillMemory(device->mix_buffer + mixplaypos, device->mix_buffer_len - mixplaypos, 0);
854 FillMemory(device->mix_buffer, mixplaypos2, 0);
855 FillMemory(buf1, size1, nfiller);
856 if (playpos && (!buf2 || !size2))
857 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__, device->playpos, device->mixpos, playpos, writepos);
858 FillMemory(buf2, size2, nfiller);
859 } else {
860 buf1 = device->buffer + device->playpos;
861 buf2 = NULL;
862 size1 = playpos - device->playpos;
863 size2 = 0;
864 FillMemory(device->mix_buffer + mixplaypos, mixplaypos2 - mixplaypos, 0);
865 FillMemory(buf1, size1, nfiller);
867 device->playpos = playpos;
869 /* find the maximum we can prebuffer from current write position */
870 maxq = (writelead < prebuff_max) ? (prebuff_max - writelead) : 0;
872 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
873 prebuff_left, device->prebuf, device->fraglen, prebuff_max, writelead);
875 /* do the mixing */
876 frag = DSOUND_MixToPrimary(device, writepos, maxq, recover, &all_stopped);
878 if (frag + writepos > device->buflen)
880 DWORD todo = device->buflen - writepos;
881 device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, todo);
882 device->normfunction(device->mix_buffer, device->buffer, frag - todo);
884 else
885 device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, frag);
887 /* update the mix position, taking wrap-around into account */
888 device->mixpos = writepos + frag;
889 device->mixpos %= device->buflen;
891 /* update prebuff left */
892 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
894 /* check if have a whole fragment */
895 if (prebuff_left >= device->fraglen){
897 /* update the wave queue */
898 DSOUND_WaveQueue(device, FALSE);
900 /* buffers are full. start playing if applicable */
901 if(device->state == STATE_STARTING){
902 TRACE("started primary buffer\n");
903 if(DSOUND_PrimaryPlay(device) != DS_OK){
904 WARN("DSOUND_PrimaryPlay failed\n");
906 else{
907 /* we are playing now */
908 device->state = STATE_PLAYING;
912 /* buffers are full. start stopping if applicable */
913 if(device->state == STATE_STOPPED){
914 TRACE("restarting primary buffer\n");
915 if(DSOUND_PrimaryPlay(device) != DS_OK){
916 WARN("DSOUND_PrimaryPlay failed\n");
918 else{
919 /* start stopping again. as soon as there is no more data, it will stop */
920 device->state = STATE_STOPPING;
925 /* if device was stopping, its for sure stopped when all buffers have stopped */
926 else if((all_stopped == TRUE) && (device->state == STATE_STOPPING)){
927 TRACE("All buffers have stopped. Stopping primary buffer\n");
928 device->state = STATE_STOPPED;
930 /* stop the primary buffer now */
931 DSOUND_PrimaryStop(device);
934 } else {
936 DSOUND_WaveQueue(device, TRUE);
938 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
939 if (device->state == STATE_STARTING) {
940 if (DSOUND_PrimaryPlay(device) != DS_OK)
941 WARN("DSOUND_PrimaryPlay failed\n");
942 else
943 device->state = STATE_PLAYING;
945 else if (device->state == STATE_STOPPING) {
946 if (DSOUND_PrimaryStop(device) != DS_OK)
947 WARN("DSOUND_PrimaryStop failed\n");
948 else
949 device->state = STATE_STOPPED;
953 LeaveCriticalSection(&(device->mixlock));
954 /* **** */
957 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD_PTR dwUser,
958 DWORD_PTR dw1, DWORD_PTR dw2)
960 DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
961 DWORD start_time = GetTickCount();
962 DWORD end_time;
963 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
964 TRACE("entering at %d\n", start_time);
966 RtlAcquireResourceShared(&(device->buffer_list_lock), TRUE);
968 if (device->ref)
969 DSOUND_PerformMix(device);
971 RtlReleaseResource(&(device->buffer_list_lock));
973 end_time = GetTickCount();
974 TRACE("completed processing at %d, duration = %d\n", end_time, end_time - start_time);