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
27 #include <math.h> /* Insomnia - pow() function */
30 #define NONAMELESSSTRUCT
31 #define NONAMELESSUNION
38 #include "wine/debug.h"
42 #include "dsound_private.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(dsound
);
47 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan
)
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
)
69 TRACE("(%p)\n",volpan
);
71 TRACE("left=%x, right=%x\n",volpan
->dwTotalLeftAmpFactor
,volpan
->dwTotalRightAmpFactor
);
72 if (volpan
->dwTotalLeftAmpFactor
==0)
75 left
=600 * log(((double)volpan
->dwTotalLeftAmpFactor
) / 0xffff) / log(2);
76 if (volpan
->dwTotalRightAmpFactor
==0)
79 right
=600 * log(((double)volpan
->dwTotalRightAmpFactor
) / 0xffff) / log(2);
82 volpan
->lVolume
=right
;
83 volpan
->dwVolAmpFactor
=volpan
->dwTotalRightAmpFactor
;
88 volpan
->dwVolAmpFactor
=volpan
->dwTotalLeftAmpFactor
;
90 if (volpan
->lVolume
< -10000)
91 volpan
->lVolume
=-10000;
92 volpan
->lPan
=right
-left
;
93 if (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)
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
;
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
))))
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
);
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
;
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;
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
)
200 LPDSBPOSITIONNOTIFY event
;
201 TRACE("(%p,%d)\n",dsb
,len
);
203 if (dsb
->nrofnotifies
== 0)
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. */
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
);
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
);
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
))
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
;
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
));
262 static UINT
cp_fields_resample(IDirectSoundBufferImpl
*dsb
,
263 UINT ostride
, UINT count
, float *freqAcc
)
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
;
303 while (idx
< fir_len
- 1) {
304 fir_copy
[fir_used
++] = fir
[idx
] * (1.0 - rem
) + fir
[idx
+ 1] * rem
;
308 assert(fir_used
<= fir_cachesize
);
309 assert(ipos
+ fir_used
<= required_input
);
311 for (channel
= 0; channel
< dsb
->mix_channels
; channel
++) {
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
);
330 static void cp_fields(IDirectSoundBufferImpl
*dsb
,
331 UINT ostride
, UINT count
, float *freqAcc
)
335 if (dsb
->freqAdjust
== 1.0)
336 adv
= cp_fields_noresample(dsb
, ostride
, count
); /* *freqAcc is unmodified */
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
)
346 dsb
->state
= STATE_STOPPED
;
350 dsb
->sec_mixpos
= ipos
;
354 * Calculate the distance between two buffer offsets, taking wraparound
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
);
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
);
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
)
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
);
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
);
431 assert(dsb
->device
->tmp_buffer_len
>= len
&& dsb
->device
->tmp_buffer
);
433 bpc
= dsb
->device
->tmp_buffer
;
436 vLeft
= dsb
->volpan
.dwTotalLeftAmpFactor
;
438 vRight
= dsb
->volpan
.dwTotalRightAmpFactor
;
442 switch (dsb
->device
->pwfx
->wBitsPerSample
) {
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;
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;
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
)
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
);
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
);
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
;
531 * Mix some frames from the given secondary buffer "dsb" into the device
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
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. */
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
;
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
);
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
;
576 /* take into account already mixed data */
577 mixlen
-= primary_done
;
579 TRACE("primary_done=%d, mixlen (primary) = %i\n", primary_done
, mixlen
);
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 */
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 void DSOUND_MixToPrimary(const DirectSoundDevice
*device
, DWORD writepos
, DWORD mixlen
, BOOL recover
, BOOL
*all_stopped
)
615 IDirectSoundBufferImpl
*dsb
;
617 /* unless we find a running buffer, all have stopped */
620 TRACE("(%d,%d,%d)\n", writepos
, mixlen
, recover
);
621 for (i
= 0; i
< device
->nrofbuffers
; i
++) {
622 dsb
= device
->buffers
[i
];
624 TRACE("MixToPrimary for %p, state=%d\n", dsb
, dsb
->state
);
626 if (dsb
->buflen
&& dsb
->state
) {
627 TRACE("Checking %p, mixlen=%d\n", dsb
, mixlen
);
628 RtlAcquireResourceShared(&dsb
->lock
, TRUE
);
629 /* if buffer is stopping it is stopped now */
630 if (dsb
->state
== STATE_STOPPING
) {
631 dsb
->state
= STATE_STOPPED
;
632 DSOUND_CheckEvent(dsb
, 0, 0);
633 } else if (dsb
->state
!= STATE_STOPPED
) {
635 /* if recovering, reset the mix position */
636 if ((dsb
->state
== STATE_STARTING
) || recover
) {
637 dsb
->primary_mixpos
= writepos
;
640 /* if the buffer was starting, it must be playing now */
641 if (dsb
->state
== STATE_STARTING
)
642 dsb
->state
= STATE_PLAYING
;
644 /* mix next buffer into the main buffer */
645 DSOUND_MixOne(dsb
, writepos
, mixlen
);
647 *all_stopped
= FALSE
;
649 RtlReleaseResource(&dsb
->lock
);
655 * Add buffers to the emulated wave device system.
657 * device = The current dsound playback device
658 * force = If TRUE, the function will buffer up as many frags as possible,
659 * even though and will ignore the actual state of the primary buffer.
664 static void DSOUND_WaveQueue(DirectSoundDevice
*device
, BOOL force
)
666 DWORD prebuf_frames
, prebuf_bytes
, read_offs_bytes
;
670 TRACE("(%p)\n", device
);
672 read_offs_bytes
= (device
->playing_offs_bytes
+ device
->in_mmdev_bytes
) % device
->buflen
;
674 TRACE("read_offs_bytes = %u, playing_offs_bytes = %u, in_mmdev_bytes: %u, prebuf = %u\n",
675 read_offs_bytes
, device
->playing_offs_bytes
, device
->in_mmdev_bytes
, device
->prebuf
);
679 if(device
->mixpos
< device
->playing_offs_bytes
)
680 prebuf_bytes
= device
->mixpos
+ device
->buflen
- device
->playing_offs_bytes
;
682 prebuf_bytes
= device
->mixpos
- device
->playing_offs_bytes
;
685 /* buffer the maximum amount of frags */
686 prebuf_bytes
= device
->prebuf
* device
->fraglen
;
688 /* limit to the queue we have left */
689 if(device
->in_mmdev_bytes
+ prebuf_bytes
> device
->prebuf
* device
->fraglen
)
690 prebuf_bytes
= device
->prebuf
* device
->fraglen
- device
->in_mmdev_bytes
;
692 TRACE("prebuf_bytes = %u\n", prebuf_bytes
);
697 device
->in_mmdev_bytes
+= prebuf_bytes
;
699 if(prebuf_bytes
+ read_offs_bytes
> device
->buflen
){
700 DWORD chunk_bytes
= device
->buflen
- read_offs_bytes
;
701 prebuf_frames
= chunk_bytes
/ device
->pwfx
->nBlockAlign
;
702 prebuf_bytes
-= chunk_bytes
;
704 prebuf_frames
= prebuf_bytes
/ device
->pwfx
->nBlockAlign
;
708 hr
= IAudioRenderClient_GetBuffer(device
->render
, prebuf_frames
, &buffer
);
710 WARN("GetBuffer failed: %08x\n", hr
);
714 memcpy(buffer
, device
->buffer
+ read_offs_bytes
,
715 prebuf_frames
* device
->pwfx
->nBlockAlign
);
717 hr
= IAudioRenderClient_ReleaseBuffer(device
->render
, prebuf_frames
, 0);
719 WARN("ReleaseBuffer failed: %08x\n", hr
);
723 /* check if anything wrapped */
724 if(prebuf_bytes
> 0){
725 prebuf_frames
= prebuf_bytes
/ device
->pwfx
->nBlockAlign
;
727 hr
= IAudioRenderClient_GetBuffer(device
->render
, prebuf_frames
, &buffer
);
729 WARN("GetBuffer failed: %08x\n", hr
);
733 memcpy(buffer
, device
->buffer
, prebuf_frames
* device
->pwfx
->nBlockAlign
);
735 hr
= IAudioRenderClient_ReleaseBuffer(device
->render
, prebuf_frames
, 0);
737 WARN("ReleaseBuffer failed: %08x\n", hr
);
742 TRACE("in_mmdev_bytes now = %i\n", device
->in_mmdev_bytes
);
746 * Perform mixing for a Direct Sound device. That is, go through all the
747 * secondary buffers (the sound bites currently playing) and mix them in
748 * to the primary buffer (the device buffer).
750 static void DSOUND_PerformMix(DirectSoundDevice
*device
)
752 UINT64 clock_pos
, clock_freq
, pos_bytes
;
756 TRACE("(%p)\n", device
);
759 EnterCriticalSection(&device
->mixlock
);
761 hr
= IAudioClock_GetFrequency(device
->clock
, &clock_freq
);
763 WARN("GetFrequency failed: %08x\n", hr
);
764 LeaveCriticalSection(&device
->mixlock
);
768 hr
= IAudioClock_GetPosition(device
->clock
, &clock_pos
, NULL
);
770 WARN("GetCurrentPadding failed: %08x\n", hr
);
771 LeaveCriticalSection(&device
->mixlock
);
775 pos_bytes
= (clock_pos
* device
->pwfx
->nSamplesPerSec
* device
->pwfx
->nBlockAlign
) / clock_freq
;
777 delta_frags
= (pos_bytes
- device
->last_pos_bytes
) / device
->fraglen
;
779 device
->playing_offs_bytes
+= delta_frags
* device
->fraglen
;
780 device
->playing_offs_bytes
%= device
->buflen
;
781 device
->in_mmdev_bytes
-= delta_frags
* device
->fraglen
;
782 device
->last_pos_bytes
= pos_bytes
- (pos_bytes
% device
->fraglen
);
785 if (device
->priolevel
!= DSSCL_WRITEPRIMARY
) {
786 BOOL recover
= FALSE
, all_stopped
= FALSE
;
787 DWORD playpos
, writepos
, writelead
, maxq
, prebuff_max
, prebuff_left
, size1
, size2
, mixplaypos
, mixplaypos2
;
791 /* the sound of silence */
792 nfiller
= device
->pwfx
->wBitsPerSample
== 8 ? 128 : 0;
794 /* get the position in the primary buffer */
795 if (DSOUND_PrimaryGetPosition(device
, &playpos
, &writepos
) != 0){
796 LeaveCriticalSection(&(device
->mixlock
));
800 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
801 playpos
,writepos
,device
->playpos
,device
->mixpos
,device
->buflen
);
802 assert(device
->playpos
< device
->buflen
);
804 mixplaypos
= DSOUND_bufpos_to_mixpos(device
, device
->playpos
);
805 mixplaypos2
= DSOUND_bufpos_to_mixpos(device
, playpos
);
807 /* calc maximum prebuff */
808 prebuff_max
= (device
->prebuf
* device
->fraglen
);
809 if (playpos
+ prebuff_max
>= device
->helfrags
* device
->fraglen
)
810 prebuff_max
+= device
->buflen
- device
->helfrags
* device
->fraglen
;
812 /* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
813 prebuff_left
= DSOUND_BufPtrDiff(device
->buflen
, device
->mixpos
, playpos
);
814 writelead
= DSOUND_BufPtrDiff(device
->buflen
, writepos
, playpos
);
816 /* check for underrun. underrun occurs when the write position passes the mix position
817 * also wipe out just-played sound data */
818 if((prebuff_left
> prebuff_max
) || (device
->state
== STATE_STOPPED
) || (device
->state
== STATE_STARTING
)){
819 if (device
->state
== STATE_STOPPING
|| device
->state
== STATE_PLAYING
)
820 WARN("Probable buffer underrun\n");
821 else TRACE("Buffer starting or buffer underrun\n");
823 /* recover mixing for all buffers */
826 /* reset mix position to write position */
827 device
->mixpos
= writepos
;
829 ZeroMemory(device
->mix_buffer
, device
->mix_buffer_len
);
830 ZeroMemory(device
->buffer
, device
->buflen
);
831 } else if (playpos
< device
->playpos
) {
832 buf1
= device
->buffer
+ device
->playpos
;
833 buf2
= device
->buffer
;
834 size1
= device
->buflen
- device
->playpos
;
836 FillMemory(device
->mix_buffer
+ mixplaypos
, device
->mix_buffer_len
- mixplaypos
, 0);
837 FillMemory(device
->mix_buffer
, mixplaypos2
, 0);
838 FillMemory(buf1
, size1
, nfiller
);
839 if (playpos
&& (!buf2
|| !size2
))
840 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__
, device
->playpos
, device
->mixpos
, playpos
, writepos
);
841 FillMemory(buf2
, size2
, nfiller
);
843 buf1
= device
->buffer
+ device
->playpos
;
845 size1
= playpos
- device
->playpos
;
847 FillMemory(device
->mix_buffer
+ mixplaypos
, mixplaypos2
- mixplaypos
, 0);
848 FillMemory(buf1
, size1
, nfiller
);
850 device
->playpos
= playpos
;
852 /* find the maximum we can prebuffer from current write position */
853 maxq
= (writelead
< prebuff_max
) ? (prebuff_max
- writelead
) : 0;
855 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
856 prebuff_left
, device
->prebuf
, device
->fraglen
, prebuff_max
, writelead
);
859 DSOUND_MixToPrimary(device
, writepos
, maxq
, recover
, &all_stopped
);
861 if (maxq
+ writepos
> device
->buflen
)
863 DWORD todo
= device
->buflen
- writepos
;
864 device
->normfunction(device
->mix_buffer
+ DSOUND_bufpos_to_mixpos(device
, writepos
), device
->buffer
+ writepos
, todo
);
865 device
->normfunction(device
->mix_buffer
, device
->buffer
, maxq
- todo
);
868 device
->normfunction(device
->mix_buffer
+ DSOUND_bufpos_to_mixpos(device
, writepos
), device
->buffer
+ writepos
, maxq
);
870 /* update the mix position, taking wrap-around into account */
871 device
->mixpos
= writepos
+ maxq
;
872 device
->mixpos
%= device
->buflen
;
874 /* update prebuff left */
875 prebuff_left
= DSOUND_BufPtrDiff(device
->buflen
, device
->mixpos
, playpos
);
877 /* check if have a whole fragment */
878 if (prebuff_left
>= device
->fraglen
){
880 /* update the wave queue */
881 DSOUND_WaveQueue(device
, FALSE
);
883 /* buffers are full. start playing if applicable */
884 if(device
->state
== STATE_STARTING
){
885 TRACE("started primary buffer\n");
886 if(DSOUND_PrimaryPlay(device
) != DS_OK
){
887 WARN("DSOUND_PrimaryPlay failed\n");
890 /* we are playing now */
891 device
->state
= STATE_PLAYING
;
895 /* buffers are full. start stopping if applicable */
896 if(device
->state
== STATE_STOPPED
){
897 TRACE("restarting primary buffer\n");
898 if(DSOUND_PrimaryPlay(device
) != DS_OK
){
899 WARN("DSOUND_PrimaryPlay failed\n");
902 /* start stopping again. as soon as there is no more data, it will stop */
903 device
->state
= STATE_STOPPING
;
908 /* if device was stopping, its for sure stopped when all buffers have stopped */
909 else if((all_stopped
== TRUE
) && (device
->state
== STATE_STOPPING
)){
910 TRACE("All buffers have stopped. Stopping primary buffer\n");
911 device
->state
= STATE_STOPPED
;
913 /* stop the primary buffer now */
914 DSOUND_PrimaryStop(device
);
919 DSOUND_WaveQueue(device
, TRUE
);
921 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
922 if (device
->state
== STATE_STARTING
) {
923 if (DSOUND_PrimaryPlay(device
) != DS_OK
)
924 WARN("DSOUND_PrimaryPlay failed\n");
926 device
->state
= STATE_PLAYING
;
928 else if (device
->state
== STATE_STOPPING
) {
929 if (DSOUND_PrimaryStop(device
) != DS_OK
)
930 WARN("DSOUND_PrimaryStop failed\n");
932 device
->state
= STATE_STOPPED
;
936 LeaveCriticalSection(&(device
->mixlock
));
940 void CALLBACK
DSOUND_timer(UINT timerID
, UINT msg
, DWORD_PTR dwUser
,
941 DWORD_PTR dw1
, DWORD_PTR dw2
)
943 DirectSoundDevice
* device
= (DirectSoundDevice
*)dwUser
;
944 DWORD start_time
= GetTickCount();
946 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID
,msg
,dwUser
,dw1
,dw2
);
947 TRACE("entering at %d\n", start_time
);
949 RtlAcquireResourceShared(&(device
->buffer_list_lock
), TRUE
);
952 DSOUND_PerformMix(device
);
954 RtlReleaseResource(&(device
->buffer_list_lock
));
956 end_time
= GetTickCount();
957 TRACE("completed processing at %d, duration = %d\n", end_time
, end_time
- start_time
);