imm32: Ignore some messages in ImmTranslateMessage.
[wine.git] / dlls / dsound / mixer.c
blobbf05805221b5ed469b9f5ab147c04f7aed54abe3
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 "wine/debug.h"
37 #include "dsound.h"
38 #include "ks.h"
39 #include "ksmedia.h"
40 #include "dsound_private.h"
41 #include "fir.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
45 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
47 double temp;
48 TRACE("(%p)\n",volpan);
50 TRACE("Vol=%ld Pan=%ld\n", volpan->lVolume, volpan->lPan);
51 /* the AmpFactors are expressed in 16.16 fixed point */
53 /* FIXME: use calculated vol and pan ampfactors */
54 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
55 volpan->dwTotalAmpFactor[0] = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
56 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
57 volpan->dwTotalAmpFactor[1] = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
59 TRACE("left = %lx, right = %lx\n", volpan->dwTotalAmpFactor[0], volpan->dwTotalAmpFactor[1]);
62 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
64 double left,right;
65 TRACE("(%p)\n",volpan);
67 TRACE("left=%lx, right=%lx\n",volpan->dwTotalAmpFactor[0],volpan->dwTotalAmpFactor[1]);
68 if (volpan->dwTotalAmpFactor[0]==0)
69 left=-10000;
70 else
71 left=600 * log(((double)volpan->dwTotalAmpFactor[0]) / 0xffff) / log(2);
72 if (volpan->dwTotalAmpFactor[1]==0)
73 right=-10000;
74 else
75 right=600 * log(((double)volpan->dwTotalAmpFactor[1]) / 0xffff) / log(2);
76 if (left<right)
77 volpan->lVolume=right;
78 else
79 volpan->lVolume=left;
80 if (volpan->lVolume < -10000)
81 volpan->lVolume=-10000;
82 volpan->lPan=right-left;
83 if (volpan->lPan < -10000)
84 volpan->lPan=-10000;
86 TRACE("Vol=%ld Pan=%ld\n", volpan->lVolume, volpan->lPan);
89 /**
90 * Recalculate the size for temporary buffer, and new writelead
91 * Should be called when one of the following things occur:
92 * - Primary buffer format is changed
93 * - This buffer format (frequency) is changed
95 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
97 DWORD ichannels = dsb->pwfx->nChannels;
98 DWORD ochannels = dsb->device->pwfx->nChannels;
99 LONG64 oldFreqAdjustDen = dsb->freqAdjustDen;
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;
133 dsb->maxwritelead = (DSBFREQUENCY_MAX / 100) * dsb->pwfx->nBlockAlign;
135 if (oldFreqAdjustDen)
136 dsb->freqAccNum = (dsb->freqAccNum * dsb->freqAdjustDen + oldFreqAdjustDen / 2) / oldFreqAdjustDen;
138 dsb->get_aux = ieee ? getbpp[4] : getbpp[dsb->pwfx->wBitsPerSample/8 - 1];
139 dsb->put_aux = putieee32;
141 dsb->get = dsb->get_aux;
142 dsb->put = dsb->put_aux;
144 if (ichannels == ochannels)
146 dsb->mix_channels = ichannels;
147 if (ichannels > 32) {
148 FIXME("Copying %lu channels is unsupported, limiting to first 32\n", ichannels);
149 dsb->mix_channels = 32;
152 else if (ichannels == 1)
154 dsb->mix_channels = 1;
156 if (ochannels == 2)
157 dsb->put = put_mono2stereo;
158 else if (ochannels == 4)
159 dsb->put = put_mono2quad;
160 else if (ochannels == 6)
161 dsb->put = put_mono2surround51;
163 else if (ochannels == 1)
165 dsb->mix_channels = 1;
166 dsb->get = get_mono;
168 else if (ichannels == 2 && ochannels == 4)
170 dsb->mix_channels = 2;
171 dsb->put = put_stereo2quad;
173 else if (ichannels == 2 && ochannels == 6)
175 dsb->mix_channels = 2;
176 dsb->put = put_stereo2surround51;
178 else if (ichannels == 6 && ochannels == 2)
180 dsb->mix_channels = 6;
181 dsb->put = put_surround512stereo;
182 dsb->put_aux = putieee32_sum;
184 else if (ichannels == 8 && ochannels == 2)
186 dsb->mix_channels = 8;
187 dsb->put = put_surround712stereo;
188 dsb->put_aux = putieee32_sum;
190 else if (ichannels == 4 && ochannels == 2)
192 dsb->mix_channels = 4;
193 dsb->put = put_quad2stereo;
194 dsb->put_aux = putieee32_sum;
196 else
198 if (ichannels > 2)
199 FIXME("Conversion from %lu to %lu channels is not implemented, falling back to stereo\n", ichannels, ochannels);
200 dsb->mix_channels = 2;
205 * Check for application callback requests for when the play position
206 * reaches certain points.
208 * The offsets that will be triggered will be those between the recorded
209 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
210 * beyond that position.
212 void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
214 int first, left, right, check;
216 if(dsb->nrofnotifies == 0)
217 return;
219 if(dsb->state == STATE_STOPPED){
220 TRACE("Stopped...\n");
221 /* DSBPN_OFFSETSTOP notifies are always at the start of the sorted array */
222 for(left = 0; left < dsb->nrofnotifies; ++left){
223 if(dsb->notifies[left].dwOffset != DSBPN_OFFSETSTOP)
224 break;
226 TRACE("Signalling %p\n", dsb->notifies[left].hEventNotify);
227 SetEvent(dsb->notifies[left].hEventNotify);
229 return;
232 for(first = 0; first < dsb->nrofnotifies && dsb->notifies[first].dwOffset == DSBPN_OFFSETSTOP; ++first)
235 if(first == dsb->nrofnotifies)
236 return;
238 check = left = first;
239 right = dsb->nrofnotifies - 1;
241 /* find leftmost notify that is greater than playpos */
242 while(left != right){
243 check = left + (right - left) / 2;
244 if(dsb->notifies[check].dwOffset < playpos)
245 left = check + 1;
246 else if(dsb->notifies[check].dwOffset > playpos)
247 right = check;
248 else{
249 left = check;
250 break;
254 TRACE("Not stopped: first notify: %u (%lu), left notify: %u (%lu), range: [%lu,%lu)\n",
255 first, dsb->notifies[first].dwOffset,
256 left, dsb->notifies[left].dwOffset,
257 playpos, (playpos + len) % dsb->buflen);
259 /* send notifications in range */
260 if(dsb->notifies[left].dwOffset >= playpos){
261 for(check = left; check < dsb->nrofnotifies; ++check){
262 if(dsb->notifies[check].dwOffset >= playpos + len)
263 break;
265 TRACE("Signalling %p (%lu)\n", dsb->notifies[check].hEventNotify, dsb->notifies[check].dwOffset);
266 SetEvent(dsb->notifies[check].hEventNotify);
270 if(playpos + len > dsb->buflen){
271 for(check = first; check < left; ++check){
272 if(dsb->notifies[check].dwOffset >= (playpos + len) % dsb->buflen)
273 break;
275 TRACE("Signalling %p (%lu)\n", dsb->notifies[check].hEventNotify, dsb->notifies[check].dwOffset);
276 SetEvent(dsb->notifies[check].hEventNotify);
281 static inline float get_current_sample(const IDirectSoundBufferImpl *dsb,
282 BYTE *buffer, DWORD buflen, DWORD mixpos, DWORD channel)
284 if (mixpos >= buflen && !(dsb->playflags & DSBPLAY_LOOPING))
285 return 0.0f;
286 return dsb->get(dsb, buffer + (mixpos % buflen), channel);
289 static UINT cp_fields_noresample(IDirectSoundBufferImpl *dsb, UINT count)
291 UINT istride = dsb->pwfx->nBlockAlign;
292 UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
293 UINT committed_samples = 0;
294 DWORD channel, i;
296 if (!secondarybuffer_is_audible(dsb))
297 return count;
299 if(dsb->use_committed) {
300 committed_samples = (dsb->writelead - dsb->committed_mixpos) / istride;
301 committed_samples = committed_samples <= count ? committed_samples : count;
304 for (i = 0; i < committed_samples; i++)
305 for (channel = 0; channel < dsb->mix_channels; channel++)
306 dsb->put(dsb, i * ostride, channel, get_current_sample(dsb, dsb->committedbuff,
307 dsb->writelead, dsb->committed_mixpos + i * istride, channel));
309 for (; i < count; i++)
310 for (channel = 0; channel < dsb->mix_channels; channel++)
311 dsb->put(dsb, i * ostride, channel, get_current_sample(dsb, dsb->buffer->memory,
312 dsb->buflen, dsb->sec_mixpos + i * istride, channel));
314 return count;
317 static UINT cp_fields_resample(IDirectSoundBufferImpl *dsb, UINT count, LONG64 *freqAccNum)
319 UINT i, channel;
320 UINT istride = dsb->pwfx->nBlockAlign;
321 UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
322 UINT committed_samples = 0;
324 LONG64 freqAcc_start = *freqAccNum;
325 LONG64 freqAcc_end = freqAcc_start + count * dsb->freqAdjustNum;
326 UINT dsbfirstep = dsb->firstep;
327 UINT channels = dsb->mix_channels;
328 UINT max_ipos = (freqAcc_start + count * dsb->freqAdjustNum) / dsb->freqAdjustDen;
330 UINT fir_cachesize = (fir_len + dsbfirstep - 2) / dsbfirstep;
331 UINT required_input = max_ipos + fir_cachesize;
332 float *intermediate, *fir_copy, *itmp;
334 DWORD len = required_input * channels;
335 len += fir_cachesize;
336 len *= sizeof(float);
338 *freqAccNum = freqAcc_end % dsb->freqAdjustDen;
340 if (!secondarybuffer_is_audible(dsb))
341 return max_ipos;
343 if (!dsb->device->cp_buffer) {
344 dsb->device->cp_buffer = malloc(len);
345 dsb->device->cp_buffer_len = len;
346 } else if (len > dsb->device->cp_buffer_len) {
347 dsb->device->cp_buffer = realloc(dsb->device->cp_buffer, len);
348 dsb->device->cp_buffer_len = len;
351 fir_copy = dsb->device->cp_buffer;
352 intermediate = fir_copy + fir_cachesize;
354 if(dsb->use_committed) {
355 committed_samples = (dsb->writelead - dsb->committed_mixpos) / istride;
356 committed_samples = committed_samples <= required_input ? committed_samples : required_input;
359 /* Important: this buffer MUST be non-interleaved
360 * if you want -msse3 to have any effect.
361 * This is good for CPU cache effects, too.
363 itmp = intermediate;
364 for (channel = 0; channel < channels; channel++) {
365 for (i = 0; i < committed_samples; i++)
366 *(itmp++) = get_current_sample(dsb, dsb->committedbuff,
367 dsb->writelead, dsb->committed_mixpos + i * istride, channel);
368 for (; i < required_input; i++)
369 *(itmp++) = get_current_sample(dsb, dsb->buffer->memory,
370 dsb->buflen, dsb->sec_mixpos + i * istride, channel);
373 for(i = 0; i < count; ++i) {
374 UINT int_fir_steps = (freqAcc_start + i * dsb->freqAdjustNum) * dsbfirstep / dsb->freqAdjustDen;
375 float total_fir_steps = (freqAcc_start + i * dsb->freqAdjustNum) * dsbfirstep / (float)dsb->freqAdjustDen;
376 UINT ipos = int_fir_steps / dsbfirstep;
378 UINT idx = (ipos + 1) * dsbfirstep - int_fir_steps - 1;
379 float rem = int_fir_steps + 1.0 - total_fir_steps;
381 int fir_used = 0;
382 while (idx < fir_len - 1) {
383 fir_copy[fir_used++] = fir[idx] * (1.0 - rem) + fir[idx + 1] * rem;
384 idx += dsb->firstep;
387 assert(fir_used <= fir_cachesize);
388 assert(ipos + fir_used <= required_input);
390 for (channel = 0; channel < dsb->mix_channels; channel++) {
391 int j;
392 float sum = 0.0;
393 float* cache = &intermediate[channel * required_input + ipos];
394 for (j = 0; j < fir_used; j++)
395 sum += fir_copy[j] * cache[j];
396 dsb->put(dsb, i * ostride, channel, sum * dsb->firgain);
400 return max_ipos;
403 static void cp_fields(IDirectSoundBufferImpl *dsb, UINT count, LONG64 *freqAccNum)
405 DWORD ipos, adv;
407 if (dsb->freqAdjustNum == dsb->freqAdjustDen)
408 adv = cp_fields_noresample(dsb, count); /* *freqAccNum is unmodified */
409 else
410 adv = cp_fields_resample(dsb, count, freqAccNum);
412 ipos = dsb->sec_mixpos + adv * dsb->pwfx->nBlockAlign;
413 if (ipos >= dsb->buflen) {
414 if (dsb->playflags & DSBPLAY_LOOPING)
415 ipos %= dsb->buflen;
416 else {
417 ipos = 0;
418 dsb->state = STATE_STOPPED;
422 dsb->sec_mixpos = ipos;
424 if(dsb->use_committed) {
425 dsb->committed_mixpos += adv * dsb->pwfx->nBlockAlign;
426 if(dsb->committed_mixpos >= dsb->writelead)
427 dsb->use_committed = FALSE;
432 * Calculate the distance between two buffer offsets, taking wraparound
433 * into account.
435 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
437 /* If these asserts fail, the problem is not here, but in the underlying code */
438 assert(ptr1 < buflen);
439 assert(ptr2 < buflen);
440 if (ptr1 >= ptr2) {
441 return ptr1 - ptr2;
442 } else {
443 return buflen + ptr1 - ptr2;
447 * Mix at most the given amount of data into the allocated temporary buffer
448 * of the given secondary buffer, starting from the dsb's first currently
449 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
450 * and bits-per-sample so that it is ideal for the primary buffer.
451 * Doesn't perform any mixing - this is a straight copy/convert operation.
453 * dsb = the secondary buffer
454 * writepos = Starting position of changed buffer
455 * len = number of bytes to resample from writepos
457 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
459 static void DSOUND_MixToTemporary(IDirectSoundBufferImpl *dsb, DWORD frames)
461 UINT size_bytes = frames * sizeof(float) * dsb->device->pwfx->nChannels;
462 HRESULT hr;
463 int i;
465 if (dsb->device->tmp_buffer_len < size_bytes || !dsb->device->tmp_buffer)
467 dsb->device->tmp_buffer_len = size_bytes;
468 dsb->device->tmp_buffer = realloc(dsb->device->tmp_buffer, size_bytes);
470 if(dsb->put_aux == putieee32_sum)
471 memset(dsb->device->tmp_buffer, 0, dsb->device->tmp_buffer_len);
473 cp_fields(dsb, frames, &dsb->freqAccNum);
475 if (size_bytes > 0) {
476 for (i = 0; i < dsb->num_filters; i++) {
477 if (dsb->filters[i].inplace) {
478 hr = IMediaObjectInPlace_Process(dsb->filters[i].inplace, size_bytes, (BYTE*)dsb->device->tmp_buffer, 0, DMO_INPLACE_NORMAL);
480 if (FAILED(hr))
481 WARN("IMediaObjectInPlace_Process failed for filter %u\n", i);
482 } else
483 WARN("filter %u has no inplace object - unsupported\n", i);
488 static void DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT frames)
490 INT i;
491 float vols[DS_MAX_CHANNELS];
492 UINT channels = dsb->device->pwfx->nChannels, chan;
494 TRACE("(%p,%d)\n",dsb,frames);
495 TRACE("left = %lx, right = %lx\n", dsb->volpan.dwTotalAmpFactor[0],
496 dsb->volpan.dwTotalAmpFactor[1]);
498 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
499 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
500 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
501 return; /* Nothing to do */
503 if (channels > DS_MAX_CHANNELS)
505 FIXME("There is no support for %u channels\n", channels);
506 return;
509 for (i = 0; i < channels; ++i)
510 vols[i] = dsb->volpan.dwTotalAmpFactor[i] / ((float)0xFFFF);
512 for(i = 0; i < frames; ++i){
513 for(chan = 0; chan < channels; ++chan){
514 dsb->device->tmp_buffer[i * channels + chan] *= vols[chan];
520 * Mix (at most) the given number of bytes into the given position of the
521 * device buffer, from the secondary buffer "dsb" (starting at the current
522 * mix position for that buffer).
524 * Returns the number of bytes actually mixed into the device buffer. This
525 * will match fraglen unless the end of the secondary buffer is reached
526 * (and it is not looping).
528 * dsb = the secondary buffer to mix from
529 * fraglen = number of bytes to mix
531 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, float *mix_buffer, DWORD frames)
533 float *ibuf;
534 DWORD oldpos;
536 TRACE("sec_mixpos=%ld/%ld\n", dsb->sec_mixpos, dsb->buflen);
537 TRACE("(%p, frames=%ld)\n",dsb,frames);
539 /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
540 oldpos = dsb->sec_mixpos;
541 DSOUND_MixToTemporary(dsb, frames);
542 ibuf = dsb->device->tmp_buffer;
544 if (secondarybuffer_is_audible(dsb)) {
545 /* Apply volume if needed */
546 DSOUND_MixerVol(dsb, frames);
548 mixieee32(ibuf, mix_buffer, frames * dsb->device->pwfx->nChannels);
551 /* check for notification positions */
552 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
553 dsb->state != STATE_STARTING) {
554 INT ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
555 DSOUND_CheckEvent(dsb, oldpos, ilen);
558 return frames;
562 * Mix some frames from the given secondary buffer "dsb" into the device
563 * primary buffer.
565 * dsb = the secondary buffer
566 * playpos = the current play position in the device buffer (primary buffer)
567 * frames = the maximum number of frames in the primary buffer to mix, from the
568 * current writepos.
570 * Returns: the number of frames beyond the writepos that were mixed.
572 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, float *mix_buffer, DWORD frames)
574 DWORD primary_done = 0;
576 TRACE("(%p, frames=%ld)\n",dsb,frames);
577 TRACE("looping=%ld, leadin=%ld\n", dsb->playflags, dsb->leadin);
579 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
580 /* FIXME: Is this needed? */
581 if (dsb->leadin && dsb->state == STATE_STARTING) {
582 if (frames > 2 * dsb->device->frag_frames) {
583 primary_done = frames - 2 * dsb->device->frag_frames;
584 frames = 2 * dsb->device->frag_frames;
585 dsb->sec_mixpos += primary_done *
586 dsb->pwfx->nBlockAlign * dsb->freqAdjustNum / dsb->freqAdjustDen;
590 dsb->leadin = FALSE;
592 TRACE("frames (primary) = %li\n", frames);
594 /* First try to mix to the end of the buffer if possible
595 * Theoretically it would allow for better optimization
597 primary_done += DSOUND_MixInBuffer(dsb, mix_buffer, frames);
599 TRACE("total mixed data=%ld\n", primary_done);
601 /* Report back the total prebuffered amount for this buffer */
602 return primary_done;
606 * For a DirectSoundDevice, go through all the currently playing buffers and
607 * mix them in to the device buffer.
609 * frames = the maximum amount to mix into the primary buffer
610 * all_stopped = reports back if all buffers have stopped
612 * Returns: the length beyond the writepos that was mixed to.
615 static void DSOUND_MixToPrimary(const DirectSoundDevice *device, float *mix_buffer, DWORD frames, BOOL *all_stopped)
617 INT i;
618 IDirectSoundBufferImpl *dsb;
620 /* unless we find a running buffer, all have stopped */
621 *all_stopped = TRUE;
623 TRACE("(frames %ld)\n", frames);
624 for (i = 0; i < device->nrofbuffers; i++) {
625 dsb = device->buffers[i];
627 TRACE("MixToPrimary for %p, state=%ld\n", dsb, dsb->state);
629 if (dsb->buflen && dsb->state) {
630 TRACE("Checking %p, frames=%ld\n", dsb, frames);
631 AcquireSRWLockShared(&dsb->lock);
632 if (dsb->state != STATE_STOPPED) {
634 /* if the buffer was starting, it must be playing now */
635 if (dsb->state == STATE_STARTING)
636 dsb->state = STATE_PLAYING;
638 /* mix next buffer into the main buffer */
639 DSOUND_MixOne(dsb, mix_buffer, frames);
641 *all_stopped = FALSE;
643 ReleaseSRWLockShared(&dsb->lock);
649 * Add buffers to the emulated wave device system.
651 * device = The current dsound playback device
652 * force = If TRUE, the function will buffer up as many frags as possible,
653 * even though and will ignore the actual state of the primary buffer.
655 * Returns: None
658 static void DSOUND_WaveQueue(DirectSoundDevice *device, LPBYTE pos, DWORD bytes)
660 BYTE *buffer;
661 HRESULT hr;
663 TRACE("(%p)\n", device);
665 hr = IAudioRenderClient_GetBuffer(device->render, bytes / device->pwfx->nBlockAlign, &buffer);
666 if(FAILED(hr)){
667 WARN("GetBuffer failed: %08lx\n", hr);
668 return;
671 memcpy(buffer, pos, bytes);
673 hr = IAudioRenderClient_ReleaseBuffer(device->render, bytes / device->pwfx->nBlockAlign, 0);
674 if(FAILED(hr)) {
675 ERR("ReleaseBuffer failed: %08lx\n", hr);
676 IAudioRenderClient_ReleaseBuffer(device->render, 0, 0);
677 return;
680 device->pad += bytes;
684 * Perform mixing for a Direct Sound device. That is, go through all the
685 * secondary buffers (the sound bites currently playing) and mix them in
686 * to the primary buffer (the device buffer).
688 * The mixing procedure goes:
690 * secondary->buffer (secondary format)
691 * =[Resample]=> device->tmp_buffer (float format)
692 * =[Volume]=> device->tmp_buffer (float format)
693 * =[Reformat]=> device->buffer (device format, skipped on float)
695 static void DSOUND_PerformMix(DirectSoundDevice *device)
697 DWORD block, pad_bytes, frames;
698 UINT32 pad_frames;
699 HRESULT hr;
701 TRACE("(%p)\n", device);
703 /* **** */
704 EnterCriticalSection(&device->mixlock);
706 hr = IAudioClient_GetCurrentPadding(device->client, &pad_frames);
707 if(FAILED(hr)){
708 WARN("GetCurrentPadding failed: %08lx\n", hr);
709 LeaveCriticalSection(&device->mixlock);
710 return;
712 block = device->pwfx->nBlockAlign;
713 pad_bytes = pad_frames * block;
714 device->playpos += device->pad - pad_bytes;
715 device->playpos %= device->buflen;
716 device->pad = pad_bytes;
718 frames = device->ac_frames - pad_frames;
719 if(!frames){
720 /* nothing to do! */
721 LeaveCriticalSection(&device->mixlock);
722 return;
724 if (frames > device->frag_frames * 3)
725 frames = device->frag_frames * 3;
727 if (device->priolevel != DSSCL_WRITEPRIMARY) {
728 BOOL all_stopped = FALSE;
729 int nfiller;
730 void *buffer = NULL;
732 /* the sound of silence */
733 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
735 /* check for underrun. underrun occurs when the write position passes the mix position
736 * also wipe out just-played sound data */
737 if (!pad_frames)
738 WARN("Probable buffer underrun\n");
740 hr = IAudioRenderClient_GetBuffer(device->render, frames, (BYTE **)&buffer);
741 if(FAILED(hr)){
742 WARN("GetBuffer failed: %08lx\n", hr);
743 LeaveCriticalSection(&device->mixlock);
744 return;
747 memset(buffer, nfiller, frames * block);
749 if (!device->normfunction)
750 DSOUND_MixToPrimary(device, buffer, frames, &all_stopped);
751 else {
752 memset(device->buffer, nfiller, device->buflen);
754 /* do the mixing */
755 DSOUND_MixToPrimary(device, (float*)device->buffer, frames, &all_stopped);
757 device->normfunction(device->buffer, buffer, frames * device->pwfx->nChannels);
760 hr = IAudioRenderClient_ReleaseBuffer(device->render, frames, 0);
761 if(FAILED(hr))
762 ERR("ReleaseBuffer failed: %08lx\n", hr);
764 device->pad += frames * block;
765 } else if (!device->stopped) {
766 DWORD writepos = (device->playpos + pad_bytes) % device->buflen;
767 DWORD bytes = frames * block;
769 if (bytes > device->buflen)
770 bytes = device->buflen;
771 if (writepos + bytes > device->buflen) {
772 DSOUND_WaveQueue(device, device->buffer + writepos, device->buflen - writepos);
773 DSOUND_WaveQueue(device, device->buffer, writepos + bytes - device->buflen);
774 } else
775 DSOUND_WaveQueue(device, device->buffer + writepos, bytes);
778 LeaveCriticalSection(&(device->mixlock));
779 /* **** */
782 DWORD CALLBACK DSOUND_mixthread(void *p)
784 DirectSoundDevice *dev = p;
785 TRACE("(%p)\n", dev);
786 SetThreadDescription(GetCurrentThread(), L"wine_dsound_mixer");
788 while (dev->ref) {
789 DWORD ret;
792 * Some audio drivers are retarded and won't fire after being
793 * stopped, add a timeout to handle this.
795 ret = WaitForSingleObject(dev->sleepev, dev->sleeptime);
796 if (ret == WAIT_FAILED)
797 WARN("wait returned error %lu %08lx!\n", GetLastError(), GetLastError());
798 else if (ret != WAIT_OBJECT_0)
799 WARN("wait returned %08lx!\n", ret);
800 if (!dev->ref)
801 break;
803 AcquireSRWLockShared(&dev->buffer_list_lock);
804 DSOUND_PerformMix(dev);
805 ReleaseSRWLockShared(&dev->buffer_list_lock);
807 return 0;