strmbase: Avoid a COM object to interface cast.
[wine.git] / dlls / dsound / mixer.c
blob309c338cd10f06681e1fda90628eabd848feeccb
1 /* DirectSound
3 * Copyright 1998 Marcus Meissner
4 * Copyright 1998 Rob Riggs
5 * Copyright 2000-2002 TransGaming Technologies, Inc.
6 * Copyright 2007 Peter Dons Tychsen
7 * Copyright 2007 Maarten Lankhorst
8 * Copyright 2011 Owen Rudge for CodeWeavers
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #include <assert.h>
26 #include <stdarg.h>
27 #include <math.h> /* Insomnia - pow() function */
29 #define COBJMACROS
31 #include "windef.h"
32 #include "winbase.h"
33 #include "mmsystem.h"
34 #include "wingdi.h"
35 #include "mmreg.h"
36 #include "winternl.h"
37 #include "wine/debug.h"
38 #include "dsound.h"
39 #include "ks.h"
40 #include "ksmedia.h"
41 #include "dsound_private.h"
42 #include "fir.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
46 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
48 double temp;
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)
65 double left,right;
66 TRACE("(%p)\n",volpan);
68 TRACE("left=%x, right=%x\n",volpan->dwTotalAmpFactor[0],volpan->dwTotalAmpFactor[1]);
69 if (volpan->dwTotalAmpFactor[0]==0)
70 left=-10000;
71 else
72 left=600 * log(((double)volpan->dwTotalAmpFactor[0]) / 0xffff) / log(2);
73 if (volpan->dwTotalAmpFactor[1]==0)
74 right=-10000;
75 else
76 right=600 * log(((double)volpan->dwTotalAmpFactor[1]) / 0xffff) / log(2);
77 if (left<right)
78 volpan->lVolume=right;
79 else
80 volpan->lVolume=left;
81 if (volpan->lVolume < -10000)
82 volpan->lVolume=-10000;
83 volpan->lPan=right-left;
84 if (volpan->lPan < -10000)
85 volpan->lPan=-10000;
87 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
90 /**
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;
101 BOOL ieee = FALSE;
103 TRACE("(%p)\n",dsb);
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))))
111 ieee = TRUE;
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;
126 } else {
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;
134 dsb->freqAccNum = 0;
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;
154 if (ochannels == 2)
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;
164 dsb->get = get_mono;
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;
176 else if (ichannels == 6 && ochannels == 2)
178 dsb->mix_channels = 6;
179 dsb->put = put_surround512stereo;
180 dsb->put_aux = putieee32_sum;
182 else if (ichannels == 4 && ochannels == 2)
184 dsb->mix_channels = 4;
185 dsb->put = put_quad2stereo;
186 dsb->put_aux = putieee32_sum;
188 else
190 if (ichannels > 2)
191 FIXME("Conversion from %u to %u channels is not implemented, falling back to stereo\n", ichannels, ochannels);
192 dsb->mix_channels = 2;
197 * Check for application callback requests for when the play position
198 * reaches certain points.
200 * The offsets that will be triggered will be those between the recorded
201 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
202 * beyond that position.
204 void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
206 int first, left, right, check;
208 if(dsb->nrofnotifies == 0)
209 return;
211 if(dsb->state == STATE_STOPPED){
212 TRACE("Stopped...\n");
213 /* DSBPN_OFFSETSTOP notifies are always at the start of the sorted array */
214 for(left = 0; left < dsb->nrofnotifies; ++left){
215 if(dsb->notifies[left].dwOffset != DSBPN_OFFSETSTOP)
216 break;
218 TRACE("Signalling %p\n", dsb->notifies[left].hEventNotify);
219 SetEvent(dsb->notifies[left].hEventNotify);
221 return;
224 for(first = 0; first < dsb->nrofnotifies && dsb->notifies[first].dwOffset == DSBPN_OFFSETSTOP; ++first)
227 if(first == dsb->nrofnotifies)
228 return;
230 check = left = first;
231 right = dsb->nrofnotifies - 1;
233 /* find leftmost notify that is greater than playpos */
234 while(left != right){
235 check = left + (right - left) / 2;
236 if(dsb->notifies[check].dwOffset < playpos)
237 left = check + 1;
238 else if(dsb->notifies[check].dwOffset > playpos)
239 right = check;
240 else{
241 left = check;
242 break;
246 TRACE("Not stopped: first notify: %u (%u), left notify: %u (%u), range: [%u,%u)\n",
247 first, dsb->notifies[first].dwOffset,
248 left, dsb->notifies[left].dwOffset,
249 playpos, (playpos + len) % dsb->buflen);
251 /* send notifications in range */
252 if(dsb->notifies[left].dwOffset >= playpos){
253 for(check = left; check < dsb->nrofnotifies; ++check){
254 if(dsb->notifies[check].dwOffset >= playpos + len)
255 break;
257 TRACE("Signalling %p (%u)\n", dsb->notifies[check].hEventNotify, dsb->notifies[check].dwOffset);
258 SetEvent(dsb->notifies[check].hEventNotify);
262 if(playpos + len > dsb->buflen){
263 for(check = first; check < left; ++check){
264 if(dsb->notifies[check].dwOffset >= (playpos + len) % dsb->buflen)
265 break;
267 TRACE("Signalling %p (%u)\n", dsb->notifies[check].hEventNotify, dsb->notifies[check].dwOffset);
268 SetEvent(dsb->notifies[check].hEventNotify);
273 static inline float get_current_sample(const IDirectSoundBufferImpl *dsb,
274 DWORD mixpos, DWORD channel)
276 if (mixpos >= dsb->buflen && !(dsb->playflags & DSBPLAY_LOOPING))
277 return 0.0f;
278 return dsb->get(dsb, mixpos % dsb->buflen, channel);
281 static UINT cp_fields_noresample(IDirectSoundBufferImpl *dsb, UINT count)
283 UINT istride = dsb->pwfx->nBlockAlign;
284 UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
285 DWORD channel, i;
286 for (i = 0; i < count; i++)
287 for (channel = 0; channel < dsb->mix_channels; channel++)
288 dsb->put(dsb, i * ostride, channel, get_current_sample(dsb,
289 dsb->sec_mixpos + i * istride, channel));
290 return count;
293 static UINT cp_fields_resample(IDirectSoundBufferImpl *dsb, UINT count, LONG64 *freqAccNum)
295 UINT i, channel;
296 UINT istride = dsb->pwfx->nBlockAlign;
297 UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
299 LONG64 freqAcc_start = *freqAccNum;
300 LONG64 freqAcc_end = freqAcc_start + count * dsb->freqAdjustNum;
301 UINT dsbfirstep = dsb->firstep;
302 UINT channels = dsb->mix_channels;
303 UINT max_ipos = (freqAcc_start + count * dsb->freqAdjustNum) / dsb->freqAdjustDen;
305 UINT fir_cachesize = (fir_len + dsbfirstep - 2) / dsbfirstep;
306 UINT required_input = max_ipos + fir_cachesize;
307 float *intermediate, *fir_copy, *itmp;
309 DWORD len = required_input * channels;
310 len += fir_cachesize;
311 len *= sizeof(float);
313 if (!dsb->device->cp_buffer) {
314 dsb->device->cp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
315 dsb->device->cp_buffer_len = len;
316 } else if (len > dsb->device->cp_buffer_len) {
317 dsb->device->cp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->cp_buffer, len);
318 dsb->device->cp_buffer_len = len;
321 fir_copy = dsb->device->cp_buffer;
322 intermediate = fir_copy + fir_cachesize;
325 /* Important: this buffer MUST be non-interleaved
326 * if you want -msse3 to have any effect.
327 * This is good for CPU cache effects, too.
329 itmp = intermediate;
330 for (channel = 0; channel < channels; channel++)
331 for (i = 0; i < required_input; i++)
332 *(itmp++) = get_current_sample(dsb,
333 dsb->sec_mixpos + i * istride, channel);
335 for(i = 0; i < count; ++i) {
336 UINT int_fir_steps = (freqAcc_start + i * dsb->freqAdjustNum) * dsbfirstep / dsb->freqAdjustDen;
337 float total_fir_steps = (freqAcc_start + i * dsb->freqAdjustNum) * dsbfirstep / (float)dsb->freqAdjustDen;
338 UINT ipos = int_fir_steps / dsbfirstep;
340 UINT idx = (ipos + 1) * dsbfirstep - int_fir_steps - 1;
341 float rem = int_fir_steps + 1.0 - total_fir_steps;
343 int fir_used = 0;
344 while (idx < fir_len - 1) {
345 fir_copy[fir_used++] = fir[idx] * (1.0 - rem) + fir[idx + 1] * rem;
346 idx += dsb->firstep;
349 assert(fir_used <= fir_cachesize);
350 assert(ipos + fir_used <= required_input);
352 for (channel = 0; channel < dsb->mix_channels; channel++) {
353 int j;
354 float sum = 0.0;
355 float* cache = &intermediate[channel * required_input + ipos];
356 for (j = 0; j < fir_used; j++)
357 sum += fir_copy[j] * cache[j];
358 dsb->put(dsb, i * ostride, channel, sum * dsb->firgain);
362 *freqAccNum = freqAcc_end % dsb->freqAdjustDen;
364 return max_ipos;
367 static void cp_fields(IDirectSoundBufferImpl *dsb, UINT count, LONG64 *freqAccNum)
369 DWORD ipos, adv;
371 if (dsb->freqAdjustNum == dsb->freqAdjustDen)
372 adv = cp_fields_noresample(dsb, count); /* *freqAccNum is unmodified */
373 else
374 adv = cp_fields_resample(dsb, count, freqAccNum);
376 ipos = dsb->sec_mixpos + adv * dsb->pwfx->nBlockAlign;
377 if (ipos >= dsb->buflen) {
378 if (dsb->playflags & DSBPLAY_LOOPING)
379 ipos %= dsb->buflen;
380 else {
381 ipos = 0;
382 dsb->state = STATE_STOPPED;
386 dsb->sec_mixpos = ipos;
390 * Calculate the distance between two buffer offsets, taking wraparound
391 * into account.
393 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
395 /* If these asserts fail, the problem is not here, but in the underlying code */
396 assert(ptr1 < buflen);
397 assert(ptr2 < buflen);
398 if (ptr1 >= ptr2) {
399 return ptr1 - ptr2;
400 } else {
401 return buflen + ptr1 - ptr2;
405 * Mix at most the given amount of data into the allocated temporary buffer
406 * of the given secondary buffer, starting from the dsb's first currently
407 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
408 * and bits-per-sample so that it is ideal for the primary buffer.
409 * Doesn't perform any mixing - this is a straight copy/convert operation.
411 * dsb = the secondary buffer
412 * writepos = Starting position of changed buffer
413 * len = number of bytes to resample from writepos
415 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
417 static void DSOUND_MixToTemporary(IDirectSoundBufferImpl *dsb, DWORD frames)
419 UINT size_bytes = frames * sizeof(float) * dsb->device->pwfx->nChannels;
420 HRESULT hr;
421 int i;
423 if (dsb->device->tmp_buffer_len < size_bytes || !dsb->device->tmp_buffer)
425 dsb->device->tmp_buffer_len = size_bytes;
426 if (dsb->device->tmp_buffer)
427 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, size_bytes);
428 else
429 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, size_bytes);
432 cp_fields(dsb, frames, &dsb->freqAccNum);
434 if (size_bytes > 0) {
435 for (i = 0; i < dsb->num_filters; i++) {
436 if (dsb->filters[i].inplace) {
437 hr = IMediaObjectInPlace_Process(dsb->filters[i].inplace, size_bytes, (BYTE*)dsb->device->tmp_buffer, 0, DMO_INPLACE_NORMAL);
439 if (FAILED(hr))
440 WARN("IMediaObjectInPlace_Process failed for filter %u\n", i);
441 } else
442 WARN("filter %u has no inplace object - unsupported\n", i);
447 static void DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT frames)
449 INT i;
450 float vols[DS_MAX_CHANNELS];
451 UINT channels = dsb->device->pwfx->nChannels, chan;
453 TRACE("(%p,%d)\n",dsb,frames);
454 TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalAmpFactor[0],
455 dsb->volpan.dwTotalAmpFactor[1]);
457 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
458 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
459 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
460 return; /* Nothing to do */
462 if (channels > DS_MAX_CHANNELS)
464 FIXME("There is no support for %u channels\n", channels);
465 return;
468 for (i = 0; i < channels; ++i)
469 vols[i] = dsb->volpan.dwTotalAmpFactor[i] / ((float)0xFFFF);
471 for(i = 0; i < frames; ++i){
472 for(chan = 0; chan < channels; ++chan){
473 dsb->device->tmp_buffer[i * channels + chan] *= vols[chan];
479 * Mix (at most) the given number of bytes into the given position of the
480 * device buffer, from the secondary buffer "dsb" (starting at the current
481 * mix position for that buffer).
483 * Returns the number of bytes actually mixed into the device buffer. This
484 * will match fraglen unless the end of the secondary buffer is reached
485 * (and it is not looping).
487 * dsb = the secondary buffer to mix from
488 * writepos = position (offset) in device buffer to write at
489 * fraglen = number of bytes to mix
491 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, float *mix_buffer, DWORD writepos, DWORD fraglen)
493 INT len = fraglen;
494 float *ibuf;
495 DWORD oldpos;
496 UINT frames = fraglen / dsb->device->pwfx->nBlockAlign;
498 TRACE("sec_mixpos=%d/%d\n", dsb->sec_mixpos, dsb->buflen);
499 TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
501 if (len % dsb->device->pwfx->nBlockAlign) {
502 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
503 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
504 len -= len % nBlockAlign; /* data alignment */
507 /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
508 oldpos = dsb->sec_mixpos;
510 if(dsb->put_aux == putieee32_sum)
511 memset(dsb->device->tmp_buffer, 0, dsb->device->tmp_buffer_len);
512 DSOUND_MixToTemporary(dsb, frames);
513 ibuf = dsb->device->tmp_buffer;
515 /* Apply volume if needed */
516 DSOUND_MixerVol(dsb, frames);
518 mixieee32(ibuf, mix_buffer, frames * dsb->device->pwfx->nChannels);
520 /* check for notification positions */
521 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
522 dsb->state != STATE_STARTING) {
523 INT ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
524 DSOUND_CheckEvent(dsb, oldpos, ilen);
527 return len;
531 * Mix some frames from the given secondary buffer "dsb" into the device
532 * primary buffer.
534 * dsb = the secondary buffer
535 * playpos = the current play position in the device buffer (primary buffer)
536 * writepos = the current safe-to-write position in the device buffer
537 * mixlen = the maximum number of bytes in the primary buffer to mix, from the
538 * current writepos.
540 * Returns: the number of bytes beyond the writepos that were mixed.
542 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, float *mix_buffer, DWORD writepos, DWORD mixlen)
544 DWORD primary_done = 0;
546 TRACE("(%p,%d,%d)\n",dsb,writepos,mixlen);
547 TRACE("writepos=%d, mixlen=%d\n", writepos, mixlen);
548 TRACE("looping=%d, leadin=%d\n", dsb->playflags, dsb->leadin);
550 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
551 /* FIXME: Is this needed? */
552 if (dsb->leadin && dsb->state == STATE_STARTING) {
553 if (mixlen > 2 * dsb->device->fraglen) {
554 primary_done = mixlen - 2 * dsb->device->fraglen;
555 mixlen = 2 * dsb->device->fraglen;
556 writepos += primary_done;
557 dsb->sec_mixpos += (primary_done / dsb->device->pwfx->nBlockAlign) *
558 dsb->pwfx->nBlockAlign * dsb->freqAdjustNum / dsb->freqAdjustDen;
562 dsb->leadin = FALSE;
564 TRACE("mixlen (primary) = %i\n", mixlen);
566 /* First try to mix to the end of the buffer if possible
567 * Theoretically it would allow for better optimization
569 primary_done += DSOUND_MixInBuffer(dsb, mix_buffer, writepos, mixlen);
571 TRACE("total mixed data=%d\n", primary_done);
573 /* Report back the total prebuffered amount for this buffer */
574 return primary_done;
578 * For a DirectSoundDevice, go through all the currently playing buffers and
579 * mix them in to the device buffer.
581 * writepos = the current safe-to-write position in the primary buffer
582 * mixlen = the maximum amount to mix into the primary buffer
583 * (beyond the current writepos)
584 * all_stopped = reports back if all buffers have stopped
586 * Returns: the length beyond the writepos that was mixed to.
589 static void DSOUND_MixToPrimary(const DirectSoundDevice *device, float *mix_buffer, DWORD writepos, DWORD mixlen, BOOL *all_stopped)
591 INT i;
592 IDirectSoundBufferImpl *dsb;
594 /* unless we find a running buffer, all have stopped */
595 *all_stopped = TRUE;
597 TRACE("(%d,%d)\n", writepos, mixlen);
598 for (i = 0; i < device->nrofbuffers; i++) {
599 dsb = device->buffers[i];
601 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
603 if (dsb->buflen && dsb->state) {
604 TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
605 RtlAcquireResourceShared(&dsb->lock, TRUE);
606 /* if buffer is stopping it is stopped now */
607 if (dsb->state == STATE_STOPPING) {
608 dsb->state = STATE_STOPPED;
609 DSOUND_CheckEvent(dsb, 0, 0);
610 } else if (dsb->state != STATE_STOPPED) {
612 /* if the buffer was starting, it must be playing now */
613 if (dsb->state == STATE_STARTING)
614 dsb->state = STATE_PLAYING;
616 /* mix next buffer into the main buffer */
617 DSOUND_MixOne(dsb, mix_buffer, writepos, mixlen);
619 *all_stopped = FALSE;
621 RtlReleaseResource(&dsb->lock);
627 * Add buffers to the emulated wave device system.
629 * device = The current dsound playback device
630 * force = If TRUE, the function will buffer up as many frags as possible,
631 * even though and will ignore the actual state of the primary buffer.
633 * Returns: None
636 static void DSOUND_WaveQueue(DirectSoundDevice *device, LPBYTE pos, DWORD bytes)
638 BYTE *buffer;
639 HRESULT hr;
641 TRACE("(%p)\n", device);
643 hr = IAudioRenderClient_GetBuffer(device->render, bytes / device->pwfx->nBlockAlign, &buffer);
644 if(FAILED(hr)){
645 WARN("GetBuffer failed: %08x\n", hr);
646 return;
649 memcpy(buffer, pos, bytes);
651 hr = IAudioRenderClient_ReleaseBuffer(device->render, bytes / device->pwfx->nBlockAlign, 0);
652 if(FAILED(hr)) {
653 ERR("ReleaseBuffer failed: %08x\n", hr);
654 IAudioRenderClient_ReleaseBuffer(device->render, 0, 0);
655 return;
658 device->pad += bytes;
662 * Perform mixing for a Direct Sound device. That is, go through all the
663 * secondary buffers (the sound bites currently playing) and mix them in
664 * to the primary buffer (the device buffer).
666 * The mixing procedure goes:
668 * secondary->buffer (secondary format)
669 * =[Resample]=> device->tmp_buffer (float format)
670 * =[Volume]=> device->tmp_buffer (float format)
671 * =[Reformat]=> device->buffer (device format, skipped on float)
673 static void DSOUND_PerformMix(DirectSoundDevice *device)
675 UINT32 pad, maxq, writepos;
676 DWORD block;
677 HRESULT hr;
679 TRACE("(%p)\n", device);
681 /* **** */
682 EnterCriticalSection(&device->mixlock);
684 hr = IAudioClient_GetCurrentPadding(device->client, &pad);
685 if(FAILED(hr)){
686 WARN("GetCurrentPadding failed: %08x\n", hr);
687 LeaveCriticalSection(&device->mixlock);
688 return;
690 block = device->pwfx->nBlockAlign;
691 pad *= block;
692 device->playpos += device->pad - pad;
693 device->playpos %= device->buflen;
694 device->pad = pad;
696 maxq = device->aclen - pad;
697 if(!maxq){
698 /* nothing to do! */
699 LeaveCriticalSection(&device->mixlock);
700 return;
702 if (maxq > device->fraglen * 3)
703 maxq = device->fraglen * 3;
705 writepos = (device->playpos + pad) % device->buflen;
707 if (device->priolevel != DSSCL_WRITEPRIMARY) {
708 BOOL all_stopped = FALSE;
709 int nfiller;
710 void *buffer = NULL;
712 /* the sound of silence */
713 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
715 /* check for underrun. underrun occurs when the write position passes the mix position
716 * also wipe out just-played sound data */
717 if (!pad)
718 WARN("Probable buffer underrun\n");
720 hr = IAudioRenderClient_GetBuffer(device->render, maxq / block, (void*)&buffer);
721 if(FAILED(hr)){
722 WARN("GetBuffer failed: %08x\n", hr);
723 LeaveCriticalSection(&device->mixlock);
724 return;
727 memset(buffer, nfiller, maxq);
729 if (!device->normfunction)
730 DSOUND_MixToPrimary(device, buffer, writepos, maxq, &all_stopped);
731 else {
732 memset(device->buffer, nfiller, device->buflen);
734 /* do the mixing */
735 DSOUND_MixToPrimary(device, (float*)device->buffer, writepos, maxq, &all_stopped);
737 device->normfunction(device->buffer, buffer, maxq);
740 hr = IAudioRenderClient_ReleaseBuffer(device->render, maxq / block, 0);
741 if(FAILED(hr))
742 ERR("ReleaseBuffer failed: %08x\n", hr);
744 device->pad += maxq;
745 } else if (!device->stopped) {
746 if (maxq > device->buflen)
747 maxq = device->buflen;
748 if (writepos + maxq > device->buflen) {
749 DSOUND_WaveQueue(device, device->buffer + writepos, device->buflen - writepos);
750 DSOUND_WaveQueue(device, device->buffer, writepos + maxq - device->buflen);
751 } else
752 DSOUND_WaveQueue(device, device->buffer + writepos, maxq);
755 LeaveCriticalSection(&(device->mixlock));
756 /* **** */
759 DWORD CALLBACK DSOUND_mixthread(void *p)
761 DirectSoundDevice *dev = p;
762 TRACE("(%p)\n", dev);
764 while (dev->ref) {
765 DWORD ret;
768 * Some audio drivers are retarded and won't fire after being
769 * stopped, add a timeout to handle this.
771 ret = WaitForSingleObject(dev->sleepev, dev->sleeptime);
772 if (ret == WAIT_FAILED)
773 WARN("wait returned error %u %08x!\n", GetLastError(), GetLastError());
774 else if (ret != WAIT_OBJECT_0)
775 WARN("wait returned %08x!\n", ret);
776 if (!dev->ref)
777 break;
779 RtlAcquireResourceShared(&(dev->buffer_list_lock), TRUE);
780 DSOUND_PerformMix(dev);
781 RtlReleaseResource(&(dev->buffer_list_lock));
783 SetEvent(dev->thread_finished);
784 return 0;