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 */
37 #include "wine/debug.h"
41 #include "dsound_private.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(dsound
);
46 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan
)
49 TRACE("(%p)\n",volpan
);
51 TRACE("Vol=%d Pan=%d\n", volpan
->lVolume
, volpan
->lPan
);
52 /* the AmpFactors are expressed in 16.16 fixed point */
54 /* FIXME: use calculated vol and pan ampfactors */
55 temp
= (double) (volpan
->lVolume
- (volpan
->lPan
> 0 ? volpan
->lPan
: 0));
56 volpan
->dwTotalAmpFactor
[0] = (ULONG
) (pow(2.0, temp
/ 600.0) * 0xffff);
57 temp
= (double) (volpan
->lVolume
+ (volpan
->lPan
< 0 ? volpan
->lPan
: 0));
58 volpan
->dwTotalAmpFactor
[1] = (ULONG
) (pow(2.0, temp
/ 600.0) * 0xffff);
60 TRACE("left = %x, right = %x\n", volpan
->dwTotalAmpFactor
[0], volpan
->dwTotalAmpFactor
[1]);
63 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan
)
66 TRACE("(%p)\n",volpan
);
68 TRACE("left=%x, right=%x\n",volpan
->dwTotalAmpFactor
[0],volpan
->dwTotalAmpFactor
[1]);
69 if (volpan
->dwTotalAmpFactor
[0]==0)
72 left
=600 * log(((double)volpan
->dwTotalAmpFactor
[0]) / 0xffff) / log(2);
73 if (volpan
->dwTotalAmpFactor
[1]==0)
76 right
=600 * log(((double)volpan
->dwTotalAmpFactor
[1]) / 0xffff) / log(2);
78 volpan
->lVolume
=right
;
81 if (volpan
->lVolume
< -10000)
82 volpan
->lVolume
=-10000;
83 volpan
->lPan
=right
-left
;
84 if (volpan
->lPan
< -10000)
87 TRACE("Vol=%d Pan=%d\n", volpan
->lVolume
, volpan
->lPan
);
91 * Recalculate the size for temporary buffer, and new writelead
92 * Should be called when one of the following things occur:
93 * - Primary buffer format is changed
94 * - This buffer format (frequency) is changed
96 void DSOUND_RecalcFormat(IDirectSoundBufferImpl
*dsb
)
98 DWORD ichannels
= dsb
->pwfx
->nChannels
;
99 DWORD ochannels
= dsb
->device
->pwfx
->nChannels
;
100 WAVEFORMATEXTENSIBLE
*pwfxe
;
105 pwfxe
= (WAVEFORMATEXTENSIBLE
*) dsb
->pwfx
;
106 dsb
->freqAdjustNum
= dsb
->freq
;
107 dsb
->freqAdjustDen
= dsb
->device
->pwfx
->nSamplesPerSec
;
109 if ((pwfxe
->Format
.wFormatTag
== WAVE_FORMAT_IEEE_FLOAT
) || ((pwfxe
->Format
.wFormatTag
== WAVE_FORMAT_EXTENSIBLE
)
110 && (IsEqualGUID(&pwfxe
->SubFormat
, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
))))
114 * Recalculate FIR step and gain.
116 * firstep says how many points of the FIR exist per one
117 * sample in the secondary buffer. firgain specifies what
118 * to multiply the FIR output by in order to attenuate it correctly.
120 if (dsb
->freqAdjustNum
/ dsb
->freqAdjustDen
> 0) {
122 * Yes, round it a bit to make sure that the
123 * linear interpolation factor never changes.
125 dsb
->firstep
= fir_step
* dsb
->freqAdjustDen
/ dsb
->freqAdjustNum
;
127 dsb
->firstep
= fir_step
;
129 dsb
->firgain
= (float)dsb
->firstep
/ fir_step
;
131 /* calculate the 10ms write lead */
132 dsb
->writelead
= (dsb
->freq
/ 100) * dsb
->pwfx
->nBlockAlign
;
136 dsb
->get_aux
= ieee
? getbpp
[4] : getbpp
[dsb
->pwfx
->wBitsPerSample
/8 - 1];
137 dsb
->put_aux
= putieee32
;
139 dsb
->get
= dsb
->get_aux
;
140 dsb
->put
= dsb
->put_aux
;
142 if (ichannels
== ochannels
)
144 dsb
->mix_channels
= ichannels
;
145 if (ichannels
> 32) {
146 FIXME("Copying %u channels is unsupported, limiting to first 32\n", ichannels
);
147 dsb
->mix_channels
= 32;
150 else if (ichannels
== 1)
152 dsb
->mix_channels
= 1;
155 dsb
->put
= put_mono2stereo
;
156 else if (ochannels
== 4)
157 dsb
->put
= put_mono2quad
;
158 else if (ochannels
== 6)
159 dsb
->put
= put_mono2surround51
;
161 else if (ochannels
== 1)
163 dsb
->mix_channels
= 1;
166 else if (ichannels
== 2 && ochannels
== 4)
168 dsb
->mix_channels
= 2;
169 dsb
->put
= put_stereo2quad
;
171 else if (ichannels
== 2 && ochannels
== 6)
173 dsb
->mix_channels
= 2;
174 dsb
->put
= put_stereo2surround51
;
179 FIXME("Conversion from %u to %u channels is not implemented, falling back to stereo\n", ichannels
, ochannels
);
180 dsb
->mix_channels
= 2;
185 * Check for application callback requests for when the play position
186 * reaches certain points.
188 * The offsets that will be triggered will be those between the recorded
189 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
190 * beyond that position.
192 void DSOUND_CheckEvent(const IDirectSoundBufferImpl
*dsb
, DWORD playpos
, int len
)
194 int first
, left
, right
, check
;
196 if(dsb
->nrofnotifies
== 0)
199 if(dsb
->state
== STATE_STOPPED
){
200 TRACE("Stopped...\n");
201 /* DSBPN_OFFSETSTOP notifies are always at the start of the sorted array */
202 for(left
= 0; left
< dsb
->nrofnotifies
; ++left
){
203 if(dsb
->notifies
[left
].dwOffset
!= DSBPN_OFFSETSTOP
)
206 TRACE("Signalling %p\n", dsb
->notifies
[left
].hEventNotify
);
207 SetEvent(dsb
->notifies
[left
].hEventNotify
);
212 for(first
= 0; first
< dsb
->nrofnotifies
&& dsb
->notifies
[first
].dwOffset
== DSBPN_OFFSETSTOP
; ++first
)
215 if(first
== dsb
->nrofnotifies
)
218 check
= left
= first
;
219 right
= dsb
->nrofnotifies
- 1;
221 /* find leftmost notify that is greater than playpos */
222 while(left
!= right
){
223 check
= left
+ (right
- left
) / 2;
224 if(dsb
->notifies
[check
].dwOffset
< playpos
)
226 else if(dsb
->notifies
[check
].dwOffset
> playpos
)
234 TRACE("Not stopped: first notify: %u (%u), left notify: %u (%u), range: [%u,%u)\n",
235 first
, dsb
->notifies
[first
].dwOffset
,
236 left
, dsb
->notifies
[left
].dwOffset
,
237 playpos
, (playpos
+ len
) % dsb
->buflen
);
239 /* send notifications in range */
240 if(dsb
->notifies
[left
].dwOffset
>= playpos
){
241 for(check
= left
; check
< dsb
->nrofnotifies
; ++check
){
242 if(dsb
->notifies
[check
].dwOffset
>= playpos
+ len
)
245 TRACE("Signalling %p (%u)\n", dsb
->notifies
[check
].hEventNotify
, dsb
->notifies
[check
].dwOffset
);
246 SetEvent(dsb
->notifies
[check
].hEventNotify
);
250 if(playpos
+ len
> dsb
->buflen
){
251 for(check
= first
; check
< left
; ++check
){
252 if(dsb
->notifies
[check
].dwOffset
>= (playpos
+ len
) % dsb
->buflen
)
255 TRACE("Signalling %p (%u)\n", dsb
->notifies
[check
].hEventNotify
, dsb
->notifies
[check
].dwOffset
);
256 SetEvent(dsb
->notifies
[check
].hEventNotify
);
261 static inline float get_current_sample(const IDirectSoundBufferImpl
*dsb
,
262 DWORD mixpos
, DWORD channel
)
264 if (mixpos
>= dsb
->buflen
&& !(dsb
->playflags
& DSBPLAY_LOOPING
))
266 return dsb
->get(dsb
, mixpos
% dsb
->buflen
, channel
);
269 static UINT
cp_fields_noresample(IDirectSoundBufferImpl
*dsb
, UINT count
)
271 UINT istride
= dsb
->pwfx
->nBlockAlign
;
272 UINT ostride
= dsb
->device
->pwfx
->nChannels
* sizeof(float);
274 for (i
= 0; i
< count
; i
++)
275 for (channel
= 0; channel
< dsb
->mix_channels
; channel
++)
276 dsb
->put(dsb
, i
* ostride
, channel
, get_current_sample(dsb
,
277 dsb
->sec_mixpos
+ i
* istride
, channel
));
281 static UINT
cp_fields_resample(IDirectSoundBufferImpl
*dsb
, UINT count
, LONG64
*freqAccNum
)
284 UINT istride
= dsb
->pwfx
->nBlockAlign
;
285 UINT ostride
= dsb
->device
->pwfx
->nChannels
* sizeof(float);
287 LONG64 freqAcc_start
= *freqAccNum
;
288 LONG64 freqAcc_end
= freqAcc_start
+ count
* dsb
->freqAdjustNum
;
289 UINT dsbfirstep
= dsb
->firstep
;
290 UINT channels
= dsb
->mix_channels
;
291 UINT max_ipos
= (freqAcc_start
+ count
* dsb
->freqAdjustNum
) / dsb
->freqAdjustDen
;
293 UINT fir_cachesize
= (fir_len
+ dsbfirstep
- 2) / dsbfirstep
;
294 UINT required_input
= max_ipos
+ fir_cachesize
;
296 float* intermediate
= HeapAlloc(GetProcessHeap(), 0,
297 sizeof(float) * required_input
* channels
);
299 float* fir_copy
= HeapAlloc(GetProcessHeap(), 0,
300 sizeof(float) * fir_cachesize
);
302 /* Important: this buffer MUST be non-interleaved
303 * if you want -msse3 to have any effect.
304 * This is good for CPU cache effects, too.
306 float* itmp
= intermediate
;
307 for (channel
= 0; channel
< channels
; channel
++)
308 for (i
= 0; i
< required_input
; i
++)
309 *(itmp
++) = get_current_sample(dsb
,
310 dsb
->sec_mixpos
+ i
* istride
, channel
);
312 for(i
= 0; i
< count
; ++i
) {
313 UINT int_fir_steps
= (freqAcc_start
+ i
* dsb
->freqAdjustNum
) * dsbfirstep
/ dsb
->freqAdjustDen
;
314 float total_fir_steps
= (freqAcc_start
+ i
* dsb
->freqAdjustNum
) * dsbfirstep
/ (float)dsb
->freqAdjustDen
;
315 UINT ipos
= int_fir_steps
/ dsbfirstep
;
317 UINT idx
= (ipos
+ 1) * dsbfirstep
- int_fir_steps
- 1;
318 float rem
= int_fir_steps
+ 1.0 - total_fir_steps
;
321 while (idx
< fir_len
- 1) {
322 fir_copy
[fir_used
++] = fir
[idx
] * (1.0 - rem
) + fir
[idx
+ 1] * rem
;
326 assert(fir_used
<= fir_cachesize
);
327 assert(ipos
+ fir_used
<= required_input
);
329 for (channel
= 0; channel
< dsb
->mix_channels
; channel
++) {
332 float* cache
= &intermediate
[channel
* required_input
+ ipos
];
333 for (j
= 0; j
< fir_used
; j
++)
334 sum
+= fir_copy
[j
] * cache
[j
];
335 dsb
->put(dsb
, i
* ostride
, channel
, sum
* dsb
->firgain
);
339 *freqAccNum
= freqAcc_end
% dsb
->freqAdjustDen
;
341 HeapFree(GetProcessHeap(), 0, fir_copy
);
342 HeapFree(GetProcessHeap(), 0, intermediate
);
347 static void cp_fields(IDirectSoundBufferImpl
*dsb
, UINT count
, LONG64
*freqAccNum
)
351 if (dsb
->freqAdjustNum
== dsb
->freqAdjustDen
)
352 adv
= cp_fields_noresample(dsb
, count
); /* *freqAccNum is unmodified */
354 adv
= cp_fields_resample(dsb
, count
, freqAccNum
);
356 ipos
= dsb
->sec_mixpos
+ adv
* dsb
->pwfx
->nBlockAlign
;
357 if (ipos
>= dsb
->buflen
) {
358 if (dsb
->playflags
& DSBPLAY_LOOPING
)
362 dsb
->state
= STATE_STOPPED
;
366 dsb
->sec_mixpos
= ipos
;
370 * Calculate the distance between two buffer offsets, taking wraparound
373 static inline DWORD
DSOUND_BufPtrDiff(DWORD buflen
, DWORD ptr1
, DWORD ptr2
)
375 /* If these asserts fail, the problem is not here, but in the underlying code */
376 assert(ptr1
< buflen
);
377 assert(ptr2
< buflen
);
381 return buflen
+ ptr1
- ptr2
;
385 * Mix at most the given amount of data into the allocated temporary buffer
386 * of the given secondary buffer, starting from the dsb's first currently
387 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
388 * and bits-per-sample so that it is ideal for the primary buffer.
389 * Doesn't perform any mixing - this is a straight copy/convert operation.
391 * dsb = the secondary buffer
392 * writepos = Starting position of changed buffer
393 * len = number of bytes to resample from writepos
395 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
397 static void DSOUND_MixToTemporary(IDirectSoundBufferImpl
*dsb
, DWORD frames
)
399 UINT size_bytes
= frames
* sizeof(float) * dsb
->device
->pwfx
->nChannels
;
403 if (dsb
->device
->tmp_buffer_len
< size_bytes
|| !dsb
->device
->tmp_buffer
)
405 dsb
->device
->tmp_buffer_len
= size_bytes
;
406 if (dsb
->device
->tmp_buffer
)
407 dsb
->device
->tmp_buffer
= HeapReAlloc(GetProcessHeap(), 0, dsb
->device
->tmp_buffer
, size_bytes
);
409 dsb
->device
->tmp_buffer
= HeapAlloc(GetProcessHeap(), 0, size_bytes
);
412 cp_fields(dsb
, frames
, &dsb
->freqAccNum
);
414 if (size_bytes
> 0) {
415 for (i
= 0; i
< dsb
->num_filters
; i
++) {
416 if (dsb
->filters
[i
].inplace
) {
417 hr
= IMediaObjectInPlace_Process(dsb
->filters
[i
].inplace
, size_bytes
, (BYTE
*)dsb
->device
->tmp_buffer
, 0, DMO_INPLACE_NORMAL
);
420 WARN("IMediaObjectInPlace_Process failed for filter %u\n", i
);
422 WARN("filter %u has no inplace object - unsupported\n", i
);
427 static void DSOUND_MixerVol(const IDirectSoundBufferImpl
*dsb
, INT frames
)
430 float vols
[DS_MAX_CHANNELS
];
431 UINT channels
= dsb
->device
->pwfx
->nChannels
, chan
;
433 TRACE("(%p,%d)\n",dsb
,frames
);
434 TRACE("left = %x, right = %x\n", dsb
->volpan
.dwTotalAmpFactor
[0],
435 dsb
->volpan
.dwTotalAmpFactor
[1]);
437 if ((!(dsb
->dsbd
.dwFlags
& DSBCAPS_CTRLPAN
) || (dsb
->volpan
.lPan
== 0)) &&
438 (!(dsb
->dsbd
.dwFlags
& DSBCAPS_CTRLVOLUME
) || (dsb
->volpan
.lVolume
== 0)) &&
439 !(dsb
->dsbd
.dwFlags
& DSBCAPS_CTRL3D
))
440 return; /* Nothing to do */
442 if (channels
> DS_MAX_CHANNELS
)
444 FIXME("There is no support for %u channels\n", channels
);
448 for (i
= 0; i
< channels
; ++i
)
449 vols
[i
] = dsb
->volpan
.dwTotalAmpFactor
[i
] / ((float)0xFFFF);
451 for(i
= 0; i
< frames
; ++i
){
452 for(chan
= 0; chan
< channels
; ++chan
){
453 dsb
->device
->tmp_buffer
[i
* channels
+ chan
] *= vols
[chan
];
459 * Mix (at most) the given number of bytes into the given position of the
460 * device buffer, from the secondary buffer "dsb" (starting at the current
461 * mix position for that buffer).
463 * Returns the number of bytes actually mixed into the device buffer. This
464 * will match fraglen unless the end of the secondary buffer is reached
465 * (and it is not looping).
467 * dsb = the secondary buffer to mix from
468 * writepos = position (offset) in device buffer to write at
469 * fraglen = number of bytes to mix
471 static DWORD
DSOUND_MixInBuffer(IDirectSoundBufferImpl
*dsb
, DWORD writepos
, DWORD fraglen
)
476 UINT frames
= fraglen
/ dsb
->device
->pwfx
->nBlockAlign
;
478 TRACE("sec_mixpos=%d/%d\n", dsb
->sec_mixpos
, dsb
->buflen
);
479 TRACE("(%p,%d,%d)\n",dsb
,writepos
,fraglen
);
481 if (len
% dsb
->device
->pwfx
->nBlockAlign
) {
482 INT nBlockAlign
= dsb
->device
->pwfx
->nBlockAlign
;
483 ERR("length not a multiple of block size, len = %d, block size = %d\n", len
, nBlockAlign
);
484 len
-= len
% nBlockAlign
; /* data alignment */
487 /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
488 oldpos
= dsb
->sec_mixpos
;
490 DSOUND_MixToTemporary(dsb
, frames
);
491 ibuf
= dsb
->device
->tmp_buffer
;
493 /* Apply volume if needed */
494 DSOUND_MixerVol(dsb
, frames
);
496 mixieee32(ibuf
, dsb
->device
->mix_buffer
, frames
* dsb
->device
->pwfx
->nChannels
);
498 /* check for notification positions */
499 if (dsb
->dsbd
.dwFlags
& DSBCAPS_CTRLPOSITIONNOTIFY
&&
500 dsb
->state
!= STATE_STARTING
) {
501 INT ilen
= DSOUND_BufPtrDiff(dsb
->buflen
, dsb
->sec_mixpos
, oldpos
);
502 DSOUND_CheckEvent(dsb
, oldpos
, ilen
);
509 * Mix some frames from the given secondary buffer "dsb" into the device
512 * dsb = the secondary buffer
513 * playpos = the current play position in the device buffer (primary buffer)
514 * writepos = the current safe-to-write position in the device buffer
515 * mixlen = the maximum number of bytes in the primary buffer to mix, from the
518 * Returns: the number of bytes beyond the writepos that were mixed.
520 static DWORD
DSOUND_MixOne(IDirectSoundBufferImpl
*dsb
, DWORD writepos
, DWORD mixlen
)
522 DWORD primary_done
= 0;
524 TRACE("(%p,%d,%d)\n",dsb
,writepos
,mixlen
);
525 TRACE("writepos=%d, mixlen=%d\n", writepos
, mixlen
);
526 TRACE("looping=%d, leadin=%d\n", dsb
->playflags
, dsb
->leadin
);
528 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
529 /* FIXME: Is this needed? */
530 if (dsb
->leadin
&& dsb
->state
== STATE_STARTING
) {
531 if (mixlen
> 2 * dsb
->device
->fraglen
) {
532 primary_done
= mixlen
- 2 * dsb
->device
->fraglen
;
533 mixlen
= 2 * dsb
->device
->fraglen
;
534 writepos
+= primary_done
;
535 dsb
->sec_mixpos
+= (primary_done
/ dsb
->device
->pwfx
->nBlockAlign
) *
536 dsb
->pwfx
->nBlockAlign
* dsb
->freqAdjustNum
/ dsb
->freqAdjustDen
;
542 TRACE("mixlen (primary) = %i\n", mixlen
);
544 /* First try to mix to the end of the buffer if possible
545 * Theoretically it would allow for better optimization
547 primary_done
+= DSOUND_MixInBuffer(dsb
, writepos
, mixlen
);
549 TRACE("total mixed data=%d\n", primary_done
);
551 /* Report back the total prebuffered amount for this buffer */
556 * For a DirectSoundDevice, go through all the currently playing buffers and
557 * mix them in to the device buffer.
559 * writepos = the current safe-to-write position in the primary buffer
560 * mixlen = the maximum amount to mix into the primary buffer
561 * (beyond the current writepos)
562 * recover = true if the sound device may have been reset and the write
563 * position in the device buffer changed
564 * all_stopped = reports back if all buffers have stopped
566 * Returns: the length beyond the writepos that was mixed to.
569 static void DSOUND_MixToPrimary(const DirectSoundDevice
*device
, DWORD writepos
, DWORD mixlen
, BOOL recover
, BOOL
*all_stopped
)
572 IDirectSoundBufferImpl
*dsb
;
574 /* unless we find a running buffer, all have stopped */
577 TRACE("(%d,%d,%d)\n", writepos
, mixlen
, recover
);
578 for (i
= 0; i
< device
->nrofbuffers
; i
++) {
579 dsb
= device
->buffers
[i
];
581 TRACE("MixToPrimary for %p, state=%d\n", dsb
, dsb
->state
);
583 if (dsb
->buflen
&& dsb
->state
) {
584 TRACE("Checking %p, mixlen=%d\n", dsb
, mixlen
);
585 RtlAcquireResourceShared(&dsb
->lock
, TRUE
);
586 /* if buffer is stopping it is stopped now */
587 if (dsb
->state
== STATE_STOPPING
) {
588 dsb
->state
= STATE_STOPPED
;
589 DSOUND_CheckEvent(dsb
, 0, 0);
590 } else if (dsb
->state
!= STATE_STOPPED
) {
592 /* if the buffer was starting, it must be playing now */
593 if (dsb
->state
== STATE_STARTING
)
594 dsb
->state
= STATE_PLAYING
;
596 /* mix next buffer into the main buffer */
597 DSOUND_MixOne(dsb
, writepos
, mixlen
);
599 *all_stopped
= FALSE
;
601 RtlReleaseResource(&dsb
->lock
);
607 * Add buffers to the emulated wave device system.
609 * device = The current dsound playback device
610 * force = If TRUE, the function will buffer up as many frags as possible,
611 * even though and will ignore the actual state of the primary buffer.
616 static void DSOUND_WaveQueue(DirectSoundDevice
*device
, BOOL force
)
618 DWORD prebuf_frames
, prebuf_bytes
, read_offs_bytes
;
622 TRACE("(%p)\n", device
);
624 read_offs_bytes
= (device
->playing_offs_bytes
+ device
->in_mmdev_bytes
) % device
->buflen
;
626 TRACE("read_offs_bytes = %u, playing_offs_bytes = %u, in_mmdev_bytes: %u, prebuf = %u\n",
627 read_offs_bytes
, device
->playing_offs_bytes
, device
->in_mmdev_bytes
, device
->prebuf
);
631 if(device
->mixpos
< device
->playing_offs_bytes
)
632 prebuf_bytes
= device
->mixpos
+ device
->buflen
- device
->playing_offs_bytes
;
634 prebuf_bytes
= device
->mixpos
- device
->playing_offs_bytes
;
637 /* buffer the maximum amount of frags */
638 prebuf_bytes
= device
->prebuf
* device
->fraglen
;
640 /* limit to the queue we have left */
641 if(device
->in_mmdev_bytes
+ prebuf_bytes
> device
->prebuf
* device
->fraglen
)
642 prebuf_bytes
= device
->prebuf
* device
->fraglen
- device
->in_mmdev_bytes
;
644 TRACE("prebuf_bytes = %u\n", prebuf_bytes
);
649 if(prebuf_bytes
+ read_offs_bytes
> device
->buflen
){
650 DWORD chunk_bytes
= device
->buflen
- read_offs_bytes
;
651 prebuf_frames
= chunk_bytes
/ device
->pwfx
->nBlockAlign
;
652 prebuf_bytes
-= chunk_bytes
;
654 prebuf_frames
= prebuf_bytes
/ device
->pwfx
->nBlockAlign
;
658 hr
= IAudioRenderClient_GetBuffer(device
->render
, prebuf_frames
, &buffer
);
660 WARN("GetBuffer failed: %08x\n", hr
);
664 memcpy(buffer
, device
->buffer
+ read_offs_bytes
,
665 prebuf_frames
* device
->pwfx
->nBlockAlign
);
667 hr
= IAudioRenderClient_ReleaseBuffer(device
->render
, prebuf_frames
, 0);
669 WARN("ReleaseBuffer failed: %08x\n", hr
);
673 device
->in_mmdev_bytes
+= prebuf_frames
* device
->pwfx
->nBlockAlign
;
675 /* check if anything wrapped */
676 if(prebuf_bytes
> 0){
677 prebuf_frames
= prebuf_bytes
/ device
->pwfx
->nBlockAlign
;
679 hr
= IAudioRenderClient_GetBuffer(device
->render
, prebuf_frames
, &buffer
);
681 WARN("GetBuffer failed: %08x\n", hr
);
685 memcpy(buffer
, device
->buffer
, prebuf_frames
* device
->pwfx
->nBlockAlign
);
687 hr
= IAudioRenderClient_ReleaseBuffer(device
->render
, prebuf_frames
, 0);
689 WARN("ReleaseBuffer failed: %08x\n", hr
);
692 device
->in_mmdev_bytes
+= prebuf_frames
* device
->pwfx
->nBlockAlign
;
695 TRACE("in_mmdev_bytes now = %i\n", device
->in_mmdev_bytes
);
699 * Perform mixing for a Direct Sound device. That is, go through all the
700 * secondary buffers (the sound bites currently playing) and mix them in
701 * to the primary buffer (the device buffer).
703 * The mixing procedure goes:
705 * secondary->buffer (secondary format)
706 * =[Resample]=> device->tmp_buffer (float format)
707 * =[Volume]=> device->tmp_buffer (float format)
708 * =[Mix]=> device->mix_buffer (float format)
709 * =[Reformat]=> device->buffer (device format)
711 static void DSOUND_PerformMix(DirectSoundDevice
*device
)
713 UINT32 pad
, to_mix_frags
, to_mix_bytes
;
716 TRACE("(%p)\n", device
);
719 EnterCriticalSection(&device
->mixlock
);
721 hr
= IAudioClient_GetCurrentPadding(device
->client
, &pad
);
723 WARN("GetCurrentPadding failed: %08x\n", hr
);
724 LeaveCriticalSection(&device
->mixlock
);
728 to_mix_frags
= device
->prebuf
- (pad
* device
->pwfx
->nBlockAlign
+ device
->fraglen
- 1) / device
->fraglen
;
730 to_mix_bytes
= to_mix_frags
* device
->fraglen
;
732 if(device
->in_mmdev_bytes
> 0){
733 DWORD delta_bytes
= min(to_mix_bytes
, device
->in_mmdev_bytes
);
734 device
->in_mmdev_bytes
-= delta_bytes
;
735 device
->playing_offs_bytes
+= delta_bytes
;
736 device
->playing_offs_bytes
%= device
->buflen
;
739 if (device
->priolevel
!= DSSCL_WRITEPRIMARY
) {
740 BOOL recover
= FALSE
, all_stopped
= FALSE
;
741 DWORD playpos
, writepos
, writelead
, maxq
, prebuff_max
, prebuff_left
, size1
, size2
;
745 /* the sound of silence */
746 nfiller
= device
->pwfx
->wBitsPerSample
== 8 ? 128 : 0;
748 /* get the position in the primary buffer */
749 if (DSOUND_PrimaryGetPosition(device
, &playpos
, &writepos
) != 0){
750 LeaveCriticalSection(&(device
->mixlock
));
754 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
755 playpos
,writepos
,device
->playpos
,device
->mixpos
,device
->buflen
);
756 assert(device
->playpos
< device
->buflen
);
758 /* calc maximum prebuff */
759 prebuff_max
= (device
->prebuf
* device
->fraglen
);
761 /* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
762 prebuff_left
= DSOUND_BufPtrDiff(device
->buflen
, device
->mixpos
, playpos
);
763 writelead
= DSOUND_BufPtrDiff(device
->buflen
, writepos
, playpos
);
765 /* check for underrun. underrun occurs when the write position passes the mix position
766 * also wipe out just-played sound data */
767 if((prebuff_left
> prebuff_max
) || (device
->state
== STATE_STOPPED
) || (device
->state
== STATE_STARTING
)){
768 if (device
->state
== STATE_STOPPING
|| device
->state
== STATE_PLAYING
)
769 WARN("Probable buffer underrun\n");
770 else TRACE("Buffer starting or buffer underrun\n");
772 /* recover mixing for all buffers */
775 /* reset mix position to write position */
776 device
->mixpos
= writepos
;
778 ZeroMemory(device
->buffer
, device
->buflen
);
779 } else if (playpos
< device
->playpos
) {
780 buf1
= device
->buffer
+ device
->playpos
;
781 buf2
= device
->buffer
;
782 size1
= device
->buflen
- device
->playpos
;
784 FillMemory(buf1
, size1
, nfiller
);
785 if (playpos
&& (!buf2
|| !size2
))
786 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__
, device
->playpos
, device
->mixpos
, playpos
, writepos
);
787 FillMemory(buf2
, size2
, nfiller
);
789 buf1
= device
->buffer
+ device
->playpos
;
791 size1
= playpos
- device
->playpos
;
793 FillMemory(buf1
, size1
, nfiller
);
795 device
->playpos
= playpos
;
797 /* find the maximum we can prebuffer from current write position */
798 maxq
= (writelead
< prebuff_max
) ? (prebuff_max
- writelead
) : 0;
800 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
801 prebuff_left
, device
->prebuf
, device
->fraglen
, prebuff_max
, writelead
);
803 ZeroMemory(device
->mix_buffer
, device
->mix_buffer_len
);
806 DSOUND_MixToPrimary(device
, writepos
, maxq
, recover
, &all_stopped
);
808 if (maxq
+ writepos
> device
->buflen
)
810 DWORD todo
= device
->buflen
- writepos
;
811 DWORD offs_float
= (todo
/ device
->pwfx
->nBlockAlign
) * device
->pwfx
->nChannels
;
812 device
->normfunction(device
->mix_buffer
, device
->buffer
+ writepos
, todo
);
813 device
->normfunction(device
->mix_buffer
+ offs_float
, device
->buffer
, maxq
- todo
);
816 device
->normfunction(device
->mix_buffer
, device
->buffer
+ writepos
, maxq
);
818 /* update the mix position, taking wrap-around into account */
819 device
->mixpos
= writepos
+ maxq
;
820 device
->mixpos
%= device
->buflen
;
822 /* update prebuff left */
823 prebuff_left
= DSOUND_BufPtrDiff(device
->buflen
, device
->mixpos
, playpos
);
825 /* check if have a whole fragment */
826 if (prebuff_left
>= device
->fraglen
){
828 /* update the wave queue */
829 DSOUND_WaveQueue(device
, FALSE
);
831 /* buffers are full. start playing if applicable */
832 if(device
->state
== STATE_STARTING
){
833 TRACE("started primary buffer\n");
834 if(DSOUND_PrimaryPlay(device
) != DS_OK
){
835 WARN("DSOUND_PrimaryPlay failed\n");
838 /* we are playing now */
839 device
->state
= STATE_PLAYING
;
843 /* buffers are full. start stopping if applicable */
844 if(device
->state
== STATE_STOPPED
){
845 TRACE("restarting primary buffer\n");
846 if(DSOUND_PrimaryPlay(device
) != DS_OK
){
847 WARN("DSOUND_PrimaryPlay failed\n");
850 /* start stopping again. as soon as there is no more data, it will stop */
851 device
->state
= STATE_STOPPING
;
856 /* if device was stopping, its for sure stopped when all buffers have stopped */
857 else if (all_stopped
&& (device
->state
== STATE_STOPPING
)) {
858 TRACE("All buffers have stopped. Stopping primary buffer\n");
859 device
->state
= STATE_STOPPED
;
861 /* stop the primary buffer now */
862 DSOUND_PrimaryStop(device
);
865 } else if (device
->state
!= STATE_STOPPED
) {
867 DSOUND_WaveQueue(device
, TRUE
);
869 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
870 if (device
->state
== STATE_STARTING
) {
871 if (DSOUND_PrimaryPlay(device
) != DS_OK
)
872 WARN("DSOUND_PrimaryPlay failed\n");
874 device
->state
= STATE_PLAYING
;
876 else if (device
->state
== STATE_STOPPING
) {
877 if (DSOUND_PrimaryStop(device
) != DS_OK
)
878 WARN("DSOUND_PrimaryStop failed\n");
880 device
->state
= STATE_STOPPED
;
884 LeaveCriticalSection(&(device
->mixlock
));
888 DWORD CALLBACK
DSOUND_mixthread(void *p
)
890 DirectSoundDevice
*dev
= p
;
891 TRACE("(%p)\n", dev
);
897 * Some audio drivers are retarded and won't fire after being
898 * stopped, add a timeout to handle this.
900 ret
= WaitForSingleObject(dev
->sleepev
, dev
->sleeptime
);
901 if (ret
== WAIT_FAILED
)
902 WARN("wait returned error %u %08x!\n", GetLastError(), GetLastError());
903 else if (ret
!= WAIT_OBJECT_0
)
904 WARN("wait returned %08x!\n", ret
);
908 RtlAcquireResourceShared(&(dev
->buffer_list_lock
), TRUE
);
909 DSOUND_PerformMix(dev
);
910 RtlReleaseResource(&(dev
->buffer_list_lock
));
912 SetEvent(dev
->thread_finished
);