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
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include <math.h> /* Insomnia - pow() function */
28 #define NONAMELESSSTRUCT
29 #define NONAMELESSUNION
34 #include "wine/debug.h"
37 #include "dsound_private.h"
39 WINE_DEFAULT_DEBUG_CHANNEL(dsound
);
41 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan
)
44 TRACE("(%p)\n",volpan
);
46 TRACE("Vol=%d Pan=%d\n", volpan
->lVolume
, volpan
->lPan
);
47 /* the AmpFactors are expressed in 16.16 fixed point */
48 volpan
->dwVolAmpFactor
= (ULONG
) (pow(2.0, volpan
->lVolume
/ 600.0) * 0xffff);
49 /* FIXME: dwPan{Left|Right}AmpFactor */
51 /* FIXME: use calculated vol and pan ampfactors */
52 temp
= (double) (volpan
->lVolume
- (volpan
->lPan
> 0 ? volpan
->lPan
: 0));
53 volpan
->dwTotalLeftAmpFactor
= (ULONG
) (pow(2.0, temp
/ 600.0) * 0xffff);
54 temp
= (double) (volpan
->lVolume
+ (volpan
->lPan
< 0 ? volpan
->lPan
: 0));
55 volpan
->dwTotalRightAmpFactor
= (ULONG
) (pow(2.0, temp
/ 600.0) * 0xffff);
57 TRACE("left = %x, right = %x\n", volpan
->dwTotalLeftAmpFactor
, volpan
->dwTotalRightAmpFactor
);
60 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan
)
63 TRACE("(%p)\n",volpan
);
65 TRACE("left=%x, right=%x\n",volpan
->dwTotalLeftAmpFactor
,volpan
->dwTotalRightAmpFactor
);
66 if (volpan
->dwTotalLeftAmpFactor
==0)
69 left
=600 * log(((double)volpan
->dwTotalLeftAmpFactor
) / 0xffff) / log(2);
70 if (volpan
->dwTotalRightAmpFactor
==0)
73 right
=600 * log(((double)volpan
->dwTotalRightAmpFactor
) / 0xffff) / log(2);
76 volpan
->lVolume
=right
;
77 volpan
->dwVolAmpFactor
=volpan
->dwTotalRightAmpFactor
;
82 volpan
->dwVolAmpFactor
=volpan
->dwTotalLeftAmpFactor
;
84 if (volpan
->lVolume
< -10000)
85 volpan
->lVolume
=-10000;
86 volpan
->lPan
=right
-left
;
87 if (volpan
->lPan
< -10000)
90 TRACE("Vol=%d Pan=%d\n", volpan
->lVolume
, volpan
->lPan
);
93 /** Convert a primary buffer position to a pointer position for device->mix_buffer
94 * device: DirectSoundDevice for which to calculate
95 * pos: Primary buffer position to converts
96 * Returns: Offset for mix_buffer
98 DWORD
DSOUND_bufpos_to_mixpos(const DirectSoundDevice
* device
, DWORD pos
)
100 DWORD ret
= pos
* 32 / device
->pwfx
->wBitsPerSample
;
101 if (device
->pwfx
->wBitsPerSample
== 32)
106 /* NOTE: Not all secpos have to always be mapped to a bufpos, other way around is always the case
107 * DWORD64 is used here because a single DWORD wouldn't be big enough to fit the freqAcc for big buffers
109 /** This function converts a 'native' sample pointer to a resampled pointer that fits for primary
110 * secmixpos is used to decide which freqAcc is needed
111 * overshot tells what the 'actual' secpos is now (optional)
113 DWORD
DSOUND_secpos_to_bufpos(const IDirectSoundBufferImpl
*dsb
, DWORD secpos
, DWORD secmixpos
, DWORD
* overshot
)
115 DWORD64 framelen
= secpos
/ dsb
->pwfx
->nBlockAlign
;
116 DWORD64 freqAdjust
= dsb
->freqAdjust
;
117 DWORD64 acc
, freqAcc
;
119 if (secpos
< secmixpos
)
120 freqAcc
= dsb
->freqAccNext
;
121 else freqAcc
= dsb
->freqAcc
;
122 acc
= (framelen
<< DSOUND_FREQSHIFT
) + (freqAdjust
- 1 - freqAcc
);
126 DWORD64 oshot
= acc
* freqAdjust
+ freqAcc
;
127 assert(oshot
>= framelen
<< DSOUND_FREQSHIFT
);
128 oshot
-= framelen
<< DSOUND_FREQSHIFT
;
129 *overshot
= (DWORD
)oshot
;
130 assert(*overshot
< dsb
->freqAdjust
);
132 return (DWORD
)acc
* dsb
->device
->pwfx
->nBlockAlign
;
135 /** Convert a resampled pointer that fits for primary to a 'native' sample pointer
136 * freqAccNext is used here rather than freqAcc: In case the app wants to fill up to
137 * the play position it won't overwrite it
139 static DWORD
DSOUND_bufpos_to_secpos(const IDirectSoundBufferImpl
*dsb
, DWORD bufpos
)
141 DWORD oAdv
= dsb
->device
->pwfx
->nBlockAlign
, iAdv
= dsb
->pwfx
->nBlockAlign
, pos
;
145 framelen
= bufpos
/oAdv
;
146 acc
= framelen
* (DWORD64
)dsb
->freqAdjust
+ (DWORD64
)dsb
->freqAccNext
;
147 acc
= acc
>> DSOUND_FREQSHIFT
;
148 pos
= (DWORD
)acc
* iAdv
;
149 if (pos
>= dsb
->buflen
)
150 /* Because of differences between freqAcc and freqAccNext, this might happen */
151 pos
= dsb
->buflen
- iAdv
;
152 TRACE("Converted %d/%d to %d/%d\n", bufpos
, dsb
->tmp_buffer_len
, pos
, dsb
->buflen
);
157 * Move freqAccNext to freqAcc, and find new values for buffer length and freqAccNext
159 static void DSOUND_RecalcFreqAcc(IDirectSoundBufferImpl
*dsb
)
161 if (!dsb
->freqneeded
) return;
162 dsb
->freqAcc
= dsb
->freqAccNext
;
163 dsb
->tmp_buffer_len
= DSOUND_secpos_to_bufpos(dsb
, dsb
->buflen
, 0, &dsb
->freqAccNext
);
164 TRACE("New freqadjust: %04x, new buflen: %d\n", dsb
->freqAccNext
, dsb
->tmp_buffer_len
);
168 * Recalculate the size for temporary buffer, and new writelead
169 * Should be called when one of the following things occur:
170 * - Primary buffer format is changed
171 * - This buffer format (frequency) is changed
173 * After this, DSOUND_MixToTemporary(dsb, 0, dsb->buflen) should
174 * be called to refill the temporary buffer with data.
176 void DSOUND_RecalcFormat(IDirectSoundBufferImpl
*dsb
)
178 BOOL needremix
= TRUE
, needresample
= (dsb
->freq
!= dsb
->device
->pwfx
->nSamplesPerSec
);
179 DWORD bAlign
= dsb
->pwfx
->nBlockAlign
, pAlign
= dsb
->device
->pwfx
->nBlockAlign
;
183 /* calculate the 10ms write lead */
184 dsb
->writelead
= (dsb
->freq
/ 100) * dsb
->pwfx
->nBlockAlign
;
186 if ((dsb
->pwfx
->wBitsPerSample
== dsb
->device
->pwfx
->wBitsPerSample
) &&
187 (dsb
->pwfx
->nChannels
== dsb
->device
->pwfx
->nChannels
) && !needresample
)
189 HeapFree(GetProcessHeap(), 0, dsb
->tmp_buffer
);
190 dsb
->tmp_buffer
= NULL
;
191 dsb
->max_buffer_len
= dsb
->freqAcc
= dsb
->freqAccNext
= 0;
192 dsb
->freqneeded
= needresample
;
194 dsb
->convert
= convertbpp
[dsb
->pwfx
->wBitsPerSample
/8 - 1][dsb
->device
->pwfx
->wBitsPerSample
/8 - 1];
196 dsb
->resampleinmixer
= FALSE
;
201 DSOUND_RecalcFreqAcc(dsb
);
203 dsb
->tmp_buffer_len
= dsb
->buflen
/ bAlign
* pAlign
;
204 dsb
->max_buffer_len
= dsb
->tmp_buffer_len
;
205 if ((dsb
->max_buffer_len
<= dsb
->device
->buflen
|| dsb
->max_buffer_len
< ds_snd_shadow_maxsize
* 1024 * 1024) && ds_snd_shadow_maxsize
>= 0)
206 dsb
->tmp_buffer
= HeapAlloc(GetProcessHeap(), 0, dsb
->max_buffer_len
);
208 FillMemory(dsb
->tmp_buffer
, dsb
->tmp_buffer_len
, dsb
->device
->pwfx
->wBitsPerSample
== 8 ? 128 : 0);
210 dsb
->resampleinmixer
= TRUE
;
212 else dsb
->max_buffer_len
= dsb
->tmp_buffer_len
= dsb
->buflen
;
213 dsb
->buf_mixpos
= DSOUND_secpos_to_bufpos(dsb
, dsb
->sec_mixpos
, 0, NULL
);
217 * Check for application callback requests for when the play position
218 * reaches certain points.
220 * The offsets that will be triggered will be those between the recorded
221 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
222 * beyond that position.
224 void DSOUND_CheckEvent(const IDirectSoundBufferImpl
*dsb
, DWORD playpos
, int len
)
228 LPDSBPOSITIONNOTIFY event
;
229 TRACE("(%p,%d)\n",dsb
,len
);
231 if (dsb
->nrofnotifies
== 0)
234 TRACE("(%p) buflen = %d, playpos = %d, len = %d\n",
235 dsb
, dsb
->buflen
, playpos
, len
);
236 for (i
= 0; i
< dsb
->nrofnotifies
; i
++) {
237 event
= dsb
->notifies
+ i
;
238 offset
= event
->dwOffset
;
239 TRACE("checking %d, position %d, event = %p\n",
240 i
, offset
, event
->hEventNotify
);
241 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
242 /* OK. [Inside DirectX, p274] */
243 /* Windows does not seem to enforce this, and some apps rely */
244 /* on that, so we can't stop there. */
246 /* This also means we can't sort the entries by offset, */
247 /* because DSBPN_OFFSETSTOP == -1 */
248 if (offset
== DSBPN_OFFSETSTOP
) {
249 if (dsb
->state
== STATE_STOPPED
) {
250 SetEvent(event
->hEventNotify
);
251 TRACE("signalled event %p (%d)\n", event
->hEventNotify
, i
);
255 if ((playpos
+ len
) >= dsb
->buflen
) {
256 if ((offset
< ((playpos
+ len
) % dsb
->buflen
)) ||
257 (offset
>= playpos
)) {
258 TRACE("signalled event %p (%d)\n", event
->hEventNotify
, i
);
259 SetEvent(event
->hEventNotify
);
262 if ((offset
>= playpos
) && (offset
< (playpos
+ len
))) {
263 TRACE("signalled event %p (%d)\n", event
->hEventNotify
, i
);
264 SetEvent(event
->hEventNotify
);
271 * Copy a single frame from the given input buffer to the given output buffer.
272 * Translate 8 <-> 16 bits and mono <-> stereo
274 static inline void cp_fields(const IDirectSoundBufferImpl
*dsb
, const BYTE
*ibuf
, BYTE
*obuf
)
276 DirectSoundDevice
*device
= dsb
->device
;
277 INT istep
= dsb
->pwfx
->wBitsPerSample
/ 8, ostep
= device
->pwfx
->wBitsPerSample
/ 8;
279 if (device
->pwfx
->nChannels
== dsb
->pwfx
->nChannels
) {
280 dsb
->convert(ibuf
, obuf
);
281 if (device
->pwfx
->nChannels
== 2)
282 dsb
->convert(ibuf
+ istep
, obuf
+ ostep
);
285 if (device
->pwfx
->nChannels
== 1 && dsb
->pwfx
->nChannels
== 2)
287 dsb
->convert(ibuf
, obuf
);
290 if (device
->pwfx
->nChannels
== 2 && dsb
->pwfx
->nChannels
== 1)
292 dsb
->convert(ibuf
, obuf
);
293 dsb
->convert(ibuf
, obuf
+ ostep
);
298 * Calculate the distance between two buffer offsets, taking wraparound
301 static inline DWORD
DSOUND_BufPtrDiff(DWORD buflen
, DWORD ptr1
, DWORD ptr2
)
303 /* If these asserts fail, the problem is not here, but in the underlying code */
304 assert(ptr1
< buflen
);
305 assert(ptr2
< buflen
);
309 return buflen
+ ptr1
- ptr2
;
313 * Mix at most the given amount of data into the allocated temporary buffer
314 * of the given secondary buffer, starting from the dsb's first currently
315 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
316 * and bits-per-sample so that it is ideal for the primary buffer.
317 * Doesn't perform any mixing - this is a straight copy/convert operation.
319 * dsb = the secondary buffer
320 * writepos = Starting position of changed buffer
321 * len = number of bytes to resample from writepos
323 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
325 void DSOUND_MixToTemporary(const IDirectSoundBufferImpl
*dsb
, DWORD writepos
, DWORD len
, BOOL inmixer
)
329 BYTE
*ibp
, *obp
, *obp_begin
;
330 INT iAdvance
= dsb
->pwfx
->nBlockAlign
;
331 INT oAdvance
= dsb
->device
->pwfx
->nBlockAlign
;
332 DWORD freqAcc
, target_writepos
= 0, overshot
, maxlen
;
334 /* We resample only when needed */
335 if ((dsb
->tmp_buffer
&& inmixer
) || (!dsb
->tmp_buffer
&& !inmixer
) || dsb
->resampleinmixer
!= inmixer
)
338 assert(writepos
+ len
<= dsb
->buflen
);
339 if (inmixer
&& writepos
+ len
< dsb
->buflen
)
340 len
+= dsb
->pwfx
->nBlockAlign
;
342 maxlen
= DSOUND_secpos_to_bufpos(dsb
, len
, 0, NULL
);
344 ibp
= dsb
->buffer
->memory
+ writepos
;
346 obp_begin
= dsb
->tmp_buffer
;
347 else if (dsb
->device
->tmp_buffer_len
< maxlen
|| !dsb
->device
->tmp_buffer
)
349 dsb
->device
->tmp_buffer_len
= maxlen
;
350 if (dsb
->device
->tmp_buffer
)
351 dsb
->device
->tmp_buffer
= HeapReAlloc(GetProcessHeap(), 0, dsb
->device
->tmp_buffer
, maxlen
);
353 dsb
->device
->tmp_buffer
= HeapAlloc(GetProcessHeap(), 0, maxlen
);
354 obp_begin
= dsb
->device
->tmp_buffer
;
357 obp_begin
= dsb
->device
->tmp_buffer
;
359 TRACE("(%p, %p)\n", dsb
, ibp
);
361 /* Check for same sample rate */
362 if (dsb
->freq
== dsb
->device
->pwfx
->nSamplesPerSec
) {
363 TRACE("(%p) Same sample rate %d = primary %d\n", dsb
,
364 dsb
->freq
, dsb
->device
->pwfx
->nSamplesPerSec
);
367 obp
+= writepos
/iAdvance
*oAdvance
;
369 for (i
= 0; i
< len
; i
+= iAdvance
) {
370 cp_fields(dsb
, ibp
, obp
);
377 /* Mix in different sample rates */
378 TRACE("(%p) Adjusting frequency: %d -> %d\n", dsb
, dsb
->freq
, dsb
->device
->pwfx
->nSamplesPerSec
);
379 size
= len
/ iAdvance
;
381 target_writepos
= DSOUND_secpos_to_bufpos(dsb
, writepos
, dsb
->sec_mixpos
, &freqAcc
);
382 overshot
= freqAcc
>> DSOUND_FREQSHIFT
;
385 if (overshot
>= size
)
388 writepos
+= overshot
* iAdvance
;
389 if (writepos
>= dsb
->buflen
)
391 ibp
= dsb
->buffer
->memory
+ writepos
;
392 freqAcc
&= (1 << DSOUND_FREQSHIFT
) - 1;
393 TRACE("Overshot: %d, freqAcc: %04x\n", overshot
, freqAcc
);
397 obp
= obp_begin
+ target_writepos
;
398 else obp
= obp_begin
;
400 /* FIXME: Small problem here when we're overwriting buf_mixpos, it then STILL uses old freqAcc, not sure if it matters or not */
402 cp_fields(dsb
, ibp
, obp
);
404 freqAcc
+= dsb
->freqAdjust
;
405 if (freqAcc
>= (1<<DSOUND_FREQSHIFT
)) {
406 ULONG adv
= (freqAcc
>>DSOUND_FREQSHIFT
);
407 freqAcc
&= (1<<DSOUND_FREQSHIFT
)-1;
408 ibp
+= adv
* iAdvance
;
414 /** Apply volume to the given soundbuffer from (primary) position writepos and length len
415 * Returns: NULL if no volume needs to be applied
416 * or else a memory handle that holds 'len' volume adjusted buffer */
417 static LPBYTE
DSOUND_MixerVol(const IDirectSoundBufferImpl
*dsb
, INT len
)
423 INT nChannels
= dsb
->device
->pwfx
->nChannels
;
424 LPBYTE mem
= (dsb
->tmp_buffer
? dsb
->tmp_buffer
: dsb
->buffer
->memory
) + dsb
->buf_mixpos
;
426 if (dsb
->resampleinmixer
)
427 mem
= dsb
->device
->tmp_buffer
;
429 TRACE("(%p,%d)\n",dsb
,len
);
430 TRACE("left = %x, right = %x\n", dsb
->volpan
.dwTotalLeftAmpFactor
,
431 dsb
->volpan
.dwTotalRightAmpFactor
);
433 if ((!(dsb
->dsbd
.dwFlags
& DSBCAPS_CTRLPAN
) || (dsb
->volpan
.lPan
== 0)) &&
434 (!(dsb
->dsbd
.dwFlags
& DSBCAPS_CTRLVOLUME
) || (dsb
->volpan
.lVolume
== 0)) &&
435 !(dsb
->dsbd
.dwFlags
& DSBCAPS_CTRL3D
))
436 return NULL
; /* Nothing to do */
438 if (nChannels
!= 1 && nChannels
!= 2)
440 FIXME("There is no support for %d channels\n", nChannels
);
444 if (dsb
->device
->pwfx
->wBitsPerSample
!= 8 && dsb
->device
->pwfx
->wBitsPerSample
!= 16)
446 FIXME("There is no support for %d bpp\n", dsb
->device
->pwfx
->wBitsPerSample
);
450 if (dsb
->device
->tmp_buffer_len
< len
|| !dsb
->device
->tmp_buffer
)
452 /* If we just resampled in DSOUND_MixToTemporary, we shouldn't need to resize here */
453 assert(!dsb
->resampleinmixer
);
454 dsb
->device
->tmp_buffer_len
= len
;
455 if (dsb
->device
->tmp_buffer
)
456 dsb
->device
->tmp_buffer
= HeapReAlloc(GetProcessHeap(), 0, dsb
->device
->tmp_buffer
, len
);
458 dsb
->device
->tmp_buffer
= HeapAlloc(GetProcessHeap(), 0, len
);
461 bpc
= dsb
->device
->tmp_buffer
;
464 vLeft
= dsb
->volpan
.dwTotalLeftAmpFactor
;
466 vRight
= dsb
->volpan
.dwTotalRightAmpFactor
;
470 switch (dsb
->device
->pwfx
->wBitsPerSample
) {
472 /* 8-bit WAV is unsigned, but we need to operate */
473 /* on signed data for this to work properly */
474 for (i
= 0; i
< len
-1; i
+=2) {
475 *(bpc
++) = (((*(mem
++) - 128) * vLeft
) >> 16) + 128;
476 *(bpc
++) = (((*(mem
++) - 128) * vRight
) >> 16) + 128;
478 if (len
% 2 == 1 && nChannels
== 1)
479 *(bpc
++) = (((*(mem
++) - 128) * vLeft
) >> 16) + 128;
482 /* 16-bit WAV is signed -- much better */
483 for (i
= 0; i
< len
-3; i
+= 4) {
484 *(bps
++) = (*(mems
++) * vLeft
) >> 16;
485 *(bps
++) = (*(mems
++) * vRight
) >> 16;
487 if (len
% 4 == 2 && nChannels
== 1)
488 *(bps
++) = ((INT
)*(mems
++) * vLeft
) >> 16;
491 return dsb
->device
->tmp_buffer
;
495 * Mix (at most) the given number of bytes into the given position of the
496 * device buffer, from the secondary buffer "dsb" (starting at the current
497 * mix position for that buffer).
499 * Returns the number of bytes actually mixed into the device buffer. This
500 * will match fraglen unless the end of the secondary buffer is reached
501 * (and it is not looping).
503 * dsb = the secondary buffer to mix from
504 * writepos = position (offset) in device buffer to write at
505 * fraglen = number of bytes to mix
507 static DWORD
DSOUND_MixInBuffer(IDirectSoundBufferImpl
*dsb
, DWORD writepos
, DWORD fraglen
)
509 INT len
= fraglen
, ilen
;
510 BYTE
*ibuf
= (dsb
->tmp_buffer
? dsb
->tmp_buffer
: dsb
->buffer
->memory
) + dsb
->buf_mixpos
, *volbuf
;
511 DWORD oldpos
, mixbufpos
;
513 TRACE("buf_mixpos=%d/%d sec_mixpos=%d/%d\n", dsb
->buf_mixpos
, dsb
->tmp_buffer_len
, dsb
->sec_mixpos
, dsb
->buflen
);
514 TRACE("(%p,%d,%d)\n",dsb
,writepos
,fraglen
);
516 assert(dsb
->buf_mixpos
+ len
<= dsb
->tmp_buffer_len
);
518 if (len
% dsb
->device
->pwfx
->nBlockAlign
) {
519 INT nBlockAlign
= dsb
->device
->pwfx
->nBlockAlign
;
520 ERR("length not a multiple of block size, len = %d, block size = %d\n", len
, nBlockAlign
);
521 len
-= len
% nBlockAlign
; /* data alignment */
524 /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
525 DSOUND_MixToTemporary(dsb
, dsb
->sec_mixpos
, DSOUND_bufpos_to_secpos(dsb
, dsb
->buf_mixpos
+len
) - dsb
->sec_mixpos
, TRUE
);
526 if (dsb
->resampleinmixer
)
527 ibuf
= dsb
->device
->tmp_buffer
;
529 /* Apply volume if needed */
530 volbuf
= DSOUND_MixerVol(dsb
, len
);
534 mixbufpos
= DSOUND_bufpos_to_mixpos(dsb
->device
, writepos
);
535 /* Now mix the temporary buffer into the devices main buffer */
536 if ((writepos
+ len
) <= dsb
->device
->buflen
)
537 dsb
->device
->mixfunction(ibuf
, dsb
->device
->mix_buffer
+ mixbufpos
, len
);
540 DWORD todo
= dsb
->device
->buflen
- writepos
;
541 dsb
->device
->mixfunction(ibuf
, dsb
->device
->mix_buffer
+ mixbufpos
, todo
);
542 dsb
->device
->mixfunction(ibuf
+ todo
, dsb
->device
->mix_buffer
, len
- todo
);
545 oldpos
= dsb
->sec_mixpos
;
546 dsb
->buf_mixpos
+= len
;
548 if (dsb
->buf_mixpos
>= dsb
->tmp_buffer_len
) {
549 if (dsb
->buf_mixpos
> dsb
->tmp_buffer_len
)
550 ERR("Mixpos (%u) past buflen (%u), capping...\n", dsb
->buf_mixpos
, dsb
->tmp_buffer_len
);
551 if (dsb
->playflags
& DSBPLAY_LOOPING
) {
552 dsb
->buf_mixpos
-= dsb
->tmp_buffer_len
;
553 } else if (dsb
->buf_mixpos
>= dsb
->tmp_buffer_len
) {
554 dsb
->buf_mixpos
= dsb
->sec_mixpos
= 0;
555 dsb
->state
= STATE_STOPPED
;
557 DSOUND_RecalcFreqAcc(dsb
);
560 dsb
->sec_mixpos
= DSOUND_bufpos_to_secpos(dsb
, dsb
->buf_mixpos
);
561 ilen
= DSOUND_BufPtrDiff(dsb
->buflen
, dsb
->sec_mixpos
, oldpos
);
562 /* check for notification positions */
563 if (dsb
->dsbd
.dwFlags
& DSBCAPS_CTRLPOSITIONNOTIFY
&&
564 dsb
->state
!= STATE_STARTING
) {
565 DSOUND_CheckEvent(dsb
, oldpos
, ilen
);
568 /* increase mix position */
569 dsb
->primary_mixpos
+= len
;
570 if (dsb
->primary_mixpos
>= dsb
->device
->buflen
)
571 dsb
->primary_mixpos
-= dsb
->device
->buflen
;
576 * Mix some frames from the given secondary buffer "dsb" into the device
579 * dsb = the secondary buffer
580 * playpos = the current play position in the device buffer (primary buffer)
581 * writepos = the current safe-to-write position in the device buffer
582 * mixlen = the maximum number of bytes in the primary buffer to mix, from the
585 * Returns: the number of bytes beyond the writepos that were mixed.
587 static DWORD
DSOUND_MixOne(IDirectSoundBufferImpl
*dsb
, DWORD writepos
, DWORD mixlen
)
589 /* The buffer's primary_mixpos may be before or after the device
590 * buffer's mixpos, but both must be ahead of writepos. */
593 TRACE("(%p,%d,%d)\n",dsb
,writepos
,mixlen
);
594 TRACE("writepos=%d, buf_mixpos=%d, primary_mixpos=%d, mixlen=%d\n", writepos
, dsb
->buf_mixpos
, dsb
->primary_mixpos
, mixlen
);
595 TRACE("looping=%d, leadin=%d, buflen=%d\n", dsb
->playflags
, dsb
->leadin
, dsb
->tmp_buffer_len
);
597 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
598 if (dsb
->leadin
&& dsb
->state
== STATE_STARTING
)
600 if (mixlen
> 2 * dsb
->device
->fraglen
)
602 dsb
->primary_mixpos
+= mixlen
- 2 * dsb
->device
->fraglen
;
603 dsb
->primary_mixpos
%= dsb
->device
->buflen
;
608 /* calculate how much pre-buffering has already been done for this buffer */
609 primary_done
= DSOUND_BufPtrDiff(dsb
->device
->buflen
, dsb
->primary_mixpos
, writepos
);
612 if(mixlen
< primary_done
)
614 /* Should *NEVER* happen */
615 ERR("Fatal error. Under/Overflow? primary_done=%d, mixpos=%d/%d (%d/%d), primary_mixpos=%d, writepos=%d, mixlen=%d\n", primary_done
,dsb
->buf_mixpos
,dsb
->tmp_buffer_len
,dsb
->sec_mixpos
, dsb
->buflen
, dsb
->primary_mixpos
, writepos
, mixlen
);
619 /* take into account already mixed data */
620 mixlen
-= primary_done
;
622 TRACE("primary_done=%d, mixlen (primary) = %i\n", primary_done
, mixlen
);
627 /* First try to mix to the end of the buffer if possible
628 * Theoretically it would allow for better optimization
630 if (mixlen
+ dsb
->buf_mixpos
>= dsb
->tmp_buffer_len
)
632 DWORD newmixed
, mixfirst
= dsb
->tmp_buffer_len
- dsb
->buf_mixpos
;
633 newmixed
= DSOUND_MixInBuffer(dsb
, dsb
->primary_mixpos
, mixfirst
);
636 if (dsb
->playflags
& DSBPLAY_LOOPING
)
637 while (newmixed
&& mixlen
)
639 mixfirst
= (dsb
->tmp_buffer_len
< mixlen
? dsb
->tmp_buffer_len
: mixlen
);
640 newmixed
= DSOUND_MixInBuffer(dsb
, dsb
->primary_mixpos
, mixfirst
);
644 else DSOUND_MixInBuffer(dsb
, dsb
->primary_mixpos
, mixlen
);
646 /* re-calculate the primary done */
647 primary_done
= DSOUND_BufPtrDiff(dsb
->device
->buflen
, dsb
->primary_mixpos
, writepos
);
649 TRACE("new primary_mixpos=%d, total mixed data=%d\n", dsb
->primary_mixpos
, primary_done
);
651 /* Report back the total prebuffered amount for this buffer */
656 * For a DirectSoundDevice, go through all the currently playing buffers and
657 * mix them in to the device buffer.
659 * writepos = the current safe-to-write position in the primary buffer
660 * mixlen = the maximum amount to mix into the primary buffer
661 * (beyond the current writepos)
662 * mustlock = Do we have to fight for lock because we otherwise risk an underrun?
663 * recover = true if the sound device may have been reset and the write
664 * position in the device buffer changed
665 * all_stopped = reports back if all buffers have stopped
667 * Returns: the length beyond the writepos that was mixed to.
670 static DWORD
DSOUND_MixToPrimary(const DirectSoundDevice
*device
, DWORD writepos
, DWORD mixlen
, BOOL mustlock
, BOOL recover
, BOOL
*all_stopped
)
674 IDirectSoundBufferImpl
*dsb
;
677 /* unless we find a running buffer, all have stopped */
680 TRACE("(%d,%d,%d)\n", writepos
, mixlen
, recover
);
681 for (i
= 0; i
< device
->nrofbuffers
; i
++) {
682 dsb
= device
->buffers
[i
];
684 TRACE("MixToPrimary for %p, state=%d\n", dsb
, dsb
->state
);
686 if (dsb
->buflen
&& dsb
->state
&& !dsb
->hwbuf
) {
687 TRACE("Checking %p, mixlen=%d\n", dsb
, mixlen
);
688 if (!RtlAcquireResourceShared(&dsb
->lock
, mustlock
))
693 /* if buffer is stopping it is stopped now */
694 if (dsb
->state
== STATE_STOPPING
) {
695 dsb
->state
= STATE_STOPPED
;
696 DSOUND_CheckEvent(dsb
, 0, 0);
697 } else if (dsb
->state
!= STATE_STOPPED
) {
699 /* if recovering, reset the mix position */
700 if ((dsb
->state
== STATE_STARTING
) || recover
) {
701 dsb
->primary_mixpos
= writepos
;
704 /* if the buffer was starting, it must be playing now */
705 if (dsb
->state
== STATE_STARTING
)
706 dsb
->state
= STATE_PLAYING
;
708 /* mix next buffer into the main buffer */
709 len
= DSOUND_MixOne(dsb
, writepos
, mixlen
);
711 if (!minlen
) minlen
= len
;
713 /* record the minimum length mixed from all buffers */
714 /* we only want to return the length which *all* buffers have mixed */
715 else if (len
) minlen
= (len
< minlen
) ? len
: minlen
;
717 *all_stopped
= FALSE
;
719 RtlReleaseResource(&dsb
->lock
);
723 TRACE("Mixed at least %d from all buffers\n", minlen
);
724 if (!gotall
) return 0;
729 * Add buffers to the emulated wave device system.
731 * device = The current dsound playback device
732 * force = If TRUE, the function will buffer up as many frags as possible,
733 * even though and will ignore the actual state of the primary buffer.
738 static void DSOUND_WaveQueue(DirectSoundDevice
*device
, BOOL force
)
740 DWORD prebuf_frags
, wave_writepos
, wave_fragpos
, i
;
741 TRACE("(%p)\n", device
);
743 /* calculate the current wave frag position */
744 wave_fragpos
= (device
->pwplay
+ device
->pwqueue
) % device
->helfrags
;
746 /* calculate the current wave write position */
747 wave_writepos
= wave_fragpos
* device
->fraglen
;
749 TRACE("wave_fragpos = %i, wave_writepos = %i, pwqueue = %i, prebuf = %i\n",
750 wave_fragpos
, wave_writepos
, device
->pwqueue
, device
->prebuf
);
754 /* check remaining prebuffered frags */
755 prebuf_frags
= device
->mixpos
/ device
->fraglen
;
756 if (prebuf_frags
== device
->helfrags
)
758 TRACE("wave_fragpos = %d, mixpos_frags = %d\n", wave_fragpos
, prebuf_frags
);
759 if (prebuf_frags
< wave_fragpos
)
760 prebuf_frags
+= device
->helfrags
;
761 prebuf_frags
-= wave_fragpos
;
762 TRACE("wanted prebuf_frags = %d\n", prebuf_frags
);
765 /* buffer the maximum amount of frags */
766 prebuf_frags
= device
->prebuf
;
768 /* limit to the queue we have left */
769 if ((prebuf_frags
+ device
->pwqueue
) > device
->prebuf
)
770 prebuf_frags
= device
->prebuf
- device
->pwqueue
;
772 TRACE("prebuf_frags = %i\n", prebuf_frags
);
775 device
->pwqueue
+= prebuf_frags
;
777 /* get out of CS when calling the wave system */
778 LeaveCriticalSection(&(device
->mixlock
));
781 /* queue up the new buffers */
782 for(i
=0; i
<prebuf_frags
; i
++){
783 TRACE("queueing wave buffer %i\n", wave_fragpos
);
784 waveOutWrite(device
->hwo
, &device
->pwave
[wave_fragpos
], sizeof(WAVEHDR
));
786 wave_fragpos
%= device
->helfrags
;
790 EnterCriticalSection(&(device
->mixlock
));
792 TRACE("queue now = %i\n", device
->pwqueue
);
796 * Perform mixing for a Direct Sound device. That is, go through all the
797 * secondary buffers (the sound bites currently playing) and mix them in
798 * to the primary buffer (the device buffer).
800 static void DSOUND_PerformMix(DirectSoundDevice
*device
)
802 TRACE("(%p)\n", device
);
805 EnterCriticalSection(&(device
->mixlock
));
807 if (device
->priolevel
!= DSSCL_WRITEPRIMARY
) {
808 BOOL recover
= FALSE
, all_stopped
= FALSE
;
809 DWORD playpos
, writepos
, writelead
, maxq
, frag
, prebuff_max
, prebuff_left
, size1
, size2
, mixplaypos
, mixplaypos2
;
811 BOOL lock
= (device
->hwbuf
&& !(device
->drvdesc
.dwFlags
& DSDDESC_DONTNEEDPRIMARYLOCK
));
812 BOOL mustlock
= FALSE
;
815 /* the sound of silence */
816 nfiller
= device
->pwfx
->wBitsPerSample
== 8 ? 128 : 0;
818 /* get the position in the primary buffer */
819 if (DSOUND_PrimaryGetPosition(device
, &playpos
, &writepos
) != 0){
820 LeaveCriticalSection(&(device
->mixlock
));
824 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
825 playpos
,writepos
,device
->playpos
,device
->mixpos
,device
->buflen
);
826 assert(device
->playpos
< device
->buflen
);
828 mixplaypos
= DSOUND_bufpos_to_mixpos(device
, device
->playpos
);
829 mixplaypos2
= DSOUND_bufpos_to_mixpos(device
, playpos
);
831 /* calc maximum prebuff */
832 prebuff_max
= (device
->prebuf
* device
->fraglen
);
833 if (!device
->hwbuf
&& playpos
+ prebuff_max
>= device
->helfrags
* device
->fraglen
)
834 prebuff_max
+= device
->buflen
- device
->helfrags
* device
->fraglen
;
836 /* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
837 prebuff_left
= DSOUND_BufPtrDiff(device
->buflen
, device
->mixpos
, playpos
);
838 writelead
= DSOUND_BufPtrDiff(device
->buflen
, writepos
, playpos
);
840 /* check for underrun. underrun occurs when the write position passes the mix position
841 * also wipe out just-played sound data */
842 if((prebuff_left
> prebuff_max
) || (device
->state
== STATE_STOPPED
) || (device
->state
== STATE_STARTING
)){
843 if (device
->state
== STATE_STOPPING
|| device
->state
== STATE_PLAYING
)
844 WARN("Probable buffer underrun\n");
845 else TRACE("Buffer starting or buffer underrun\n");
847 /* recover mixing for all buffers */
850 /* reset mix position to write position */
851 device
->mixpos
= writepos
;
853 ZeroMemory(device
->mix_buffer
, device
->mix_buffer_len
);
854 ZeroMemory(device
->buffer
, device
->buflen
);
855 } else if (playpos
< device
->playpos
) {
856 buf1
= device
->buffer
+ device
->playpos
;
857 buf2
= device
->buffer
;
858 size1
= device
->buflen
- device
->playpos
;
860 FillMemory(device
->mix_buffer
+ mixplaypos
, device
->mix_buffer_len
- mixplaypos
, 0);
861 FillMemory(device
->mix_buffer
, mixplaypos2
, 0);
863 IDsDriverBuffer_Lock(device
->hwbuf
, &buf1
, &size1
, &buf2
, &size2
, device
->playpos
, size1
+size2
, 0);
864 FillMemory(buf1
, size1
, nfiller
);
865 if (playpos
&& (!buf2
|| !size2
))
866 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__
, device
->playpos
, device
->mixpos
, playpos
, writepos
);
867 FillMemory(buf2
, size2
, nfiller
);
869 IDsDriverBuffer_Unlock(device
->hwbuf
, buf1
, size1
, buf2
, size2
);
871 buf1
= device
->buffer
+ device
->playpos
;
873 size1
= playpos
- device
->playpos
;
875 FillMemory(device
->mix_buffer
+ mixplaypos
, mixplaypos2
- mixplaypos
, 0);
877 IDsDriverBuffer_Lock(device
->hwbuf
, &buf1
, &size1
, &buf2
, &size2
, device
->playpos
, size1
+size2
, 0);
878 FillMemory(buf1
, size1
, nfiller
);
881 FIXME("%d: There should be no additional buffer here!!\n", __LINE__
);
882 FillMemory(buf2
, size2
, nfiller
);
885 IDsDriverBuffer_Unlock(device
->hwbuf
, buf1
, size1
, buf2
, size2
);
887 device
->playpos
= playpos
;
889 /* find the maximum we can prebuffer from current write position */
890 maxq
= (writelead
< prebuff_max
) ? (prebuff_max
- writelead
) : 0;
892 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
893 prebuff_left
, device
->prebuf
, device
->fraglen
, prebuff_max
, writelead
);
895 /* Do we risk an 'underrun' if we don't advance pointer? */
896 if (writelead
/device
->fraglen
<= ds_snd_queue_min
|| recover
)
900 IDsDriverBuffer_Lock(device
->hwbuf
, &buf1
, &size1
, &buf2
, &size2
, writepos
, maxq
, 0);
903 frag
= DSOUND_MixToPrimary(device
, writepos
, maxq
, mustlock
, recover
, &all_stopped
);
905 if (frag
+ writepos
> device
->buflen
)
907 DWORD todo
= device
->buflen
- writepos
;
908 device
->normfunction(device
->mix_buffer
+ DSOUND_bufpos_to_mixpos(device
, writepos
), device
->buffer
+ writepos
, todo
);
909 device
->normfunction(device
->mix_buffer
, device
->buffer
, frag
- todo
);
912 device
->normfunction(device
->mix_buffer
+ DSOUND_bufpos_to_mixpos(device
, writepos
), device
->buffer
+ writepos
, frag
);
914 /* update the mix position, taking wrap-around into account */
915 device
->mixpos
= writepos
+ frag
;
916 device
->mixpos
%= device
->buflen
;
920 DWORD frag2
= (frag
> size1
? frag
- size1
: 0);
924 FIXME("Buffering too much! (%d, %d, %d, %d)\n", maxq
, frag
, size2
, frag2
- size2
);
927 IDsDriverBuffer_Unlock(device
->hwbuf
, buf1
, frag
, buf2
, frag2
);
930 /* update prebuff left */
931 prebuff_left
= DSOUND_BufPtrDiff(device
->buflen
, device
->mixpos
, playpos
);
933 /* check if have a whole fragment */
934 if (prebuff_left
>= device
->fraglen
){
936 /* update the wave queue if using wave system */
938 DSOUND_WaveQueue(device
, FALSE
);
940 /* buffers are full. start playing if applicable */
941 if(device
->state
== STATE_STARTING
){
942 TRACE("started primary buffer\n");
943 if(DSOUND_PrimaryPlay(device
) != DS_OK
){
944 WARN("DSOUND_PrimaryPlay failed\n");
947 /* we are playing now */
948 device
->state
= STATE_PLAYING
;
952 /* buffers are full. start stopping if applicable */
953 if(device
->state
== STATE_STOPPED
){
954 TRACE("restarting primary buffer\n");
955 if(DSOUND_PrimaryPlay(device
) != DS_OK
){
956 WARN("DSOUND_PrimaryPlay failed\n");
959 /* start stopping again. as soon as there is no more data, it will stop */
960 device
->state
= STATE_STOPPING
;
965 /* if device was stopping, its for sure stopped when all buffers have stopped */
966 else if((all_stopped
== TRUE
) && (device
->state
== STATE_STOPPING
)){
967 TRACE("All buffers have stopped. Stopping primary buffer\n");
968 device
->state
= STATE_STOPPED
;
970 /* stop the primary buffer now */
971 DSOUND_PrimaryStop(device
);
976 /* update the wave queue if using wave system */
978 DSOUND_WaveQueue(device
, TRUE
);
980 /* Keep alsa happy, which needs GetPosition called once every 10 ms */
981 IDsDriverBuffer_GetPosition(device
->hwbuf
, NULL
, NULL
);
983 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
984 if (device
->state
== STATE_STARTING
) {
985 if (DSOUND_PrimaryPlay(device
) != DS_OK
)
986 WARN("DSOUND_PrimaryPlay failed\n");
988 device
->state
= STATE_PLAYING
;
990 else if (device
->state
== STATE_STOPPING
) {
991 if (DSOUND_PrimaryStop(device
) != DS_OK
)
992 WARN("DSOUND_PrimaryStop failed\n");
994 device
->state
= STATE_STOPPED
;
998 LeaveCriticalSection(&(device
->mixlock
));
1002 void CALLBACK
DSOUND_timer(UINT timerID
, UINT msg
, DWORD_PTR dwUser
,
1003 DWORD_PTR dw1
, DWORD_PTR dw2
)
1005 DirectSoundDevice
* device
= (DirectSoundDevice
*)dwUser
;
1006 DWORD start_time
= GetTickCount();
1008 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID
,msg
,dwUser
,dw1
,dw2
);
1009 TRACE("entering at %d\n", start_time
);
1011 if (DSOUND_renderer
[device
->drvdesc
.dnDevNode
] != device
) {
1012 ERR("dsound died without killing us?\n");
1013 timeKillEvent(timerID
);
1014 timeEndPeriod(DS_TIME_RES
);
1018 RtlAcquireResourceShared(&(device
->buffer_list_lock
), TRUE
);
1021 DSOUND_PerformMix(device
);
1023 RtlReleaseResource(&(device
->buffer_list_lock
));
1025 end_time
= GetTickCount();
1026 TRACE("completed processing at %d, duration = %d\n", end_time
, end_time
- start_time
);
1029 void CALLBACK
DSOUND_callback(HWAVEOUT hwo
, UINT msg
, DWORD dwUser
, DWORD dw1
, DWORD dw2
)
1031 DirectSoundDevice
* device
= (DirectSoundDevice
*)dwUser
;
1032 TRACE("(%p,%x,%x,%x,%x)\n",hwo
,msg
,dwUser
,dw1
,dw2
);
1033 TRACE("entering at %d, msg=%08x(%s)\n", GetTickCount(), msg
,
1034 msg
==MM_WOM_DONE
? "MM_WOM_DONE" : msg
==MM_WOM_CLOSE
? "MM_WOM_CLOSE" :
1035 msg
==MM_WOM_OPEN
? "MM_WOM_OPEN" : "UNKNOWN");
1037 /* check if packet completed from wave driver */
1038 if (msg
== MM_WOM_DONE
) {
1041 EnterCriticalSection(&(device
->mixlock
));
1043 TRACE("done playing primary pos=%d\n", device
->pwplay
* device
->fraglen
);
1045 /* update playpos */
1047 device
->pwplay
%= device
->helfrags
;
1050 if(device
->pwqueue
== 0){
1051 ERR("Wave queue corrupted!\n");
1057 LeaveCriticalSection(&(device
->mixlock
));
1060 TRACE("completed\n");