ddraw/tests: Move the capability tests for enumerated devices.
[wine.git] / dlls / dsound / mixer.c
blob05b2bfbf8c3465b7239568f52fbcb1f2a2ca12cc
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 WAVEFORMATEXTENSIBLE *pwfxe;
100 BOOL ieee = FALSE;
102 TRACE("(%p)\n",dsb);
104 pwfxe = (WAVEFORMATEXTENSIBLE *) dsb->pwfx;
105 dsb->freqAdjustNum = dsb->freq;
106 dsb->freqAdjustDen = dsb->device->pwfx->nSamplesPerSec;
108 if ((pwfxe->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) || ((pwfxe->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
109 && (IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))))
110 ieee = TRUE;
113 * Recalculate FIR step and gain.
115 * firstep says how many points of the FIR exist per one
116 * sample in the secondary buffer. firgain specifies what
117 * to multiply the FIR output by in order to attenuate it correctly.
119 if (dsb->freqAdjustNum / dsb->freqAdjustDen > 0) {
121 * Yes, round it a bit to make sure that the
122 * linear interpolation factor never changes.
124 dsb->firstep = fir_step * dsb->freqAdjustDen / dsb->freqAdjustNum;
125 } else {
126 dsb->firstep = fir_step;
128 dsb->firgain = (float)dsb->firstep / fir_step;
130 /* calculate the 10ms write lead */
131 dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
133 dsb->freqAccNum = 0;
135 dsb->get_aux = ieee ? getbpp[4] : getbpp[dsb->pwfx->wBitsPerSample/8 - 1];
136 dsb->put_aux = putieee32;
138 dsb->get = dsb->get_aux;
139 dsb->put = dsb->put_aux;
141 if (ichannels == ochannels)
143 dsb->mix_channels = ichannels;
144 if (ichannels > 32) {
145 FIXME("Copying %lu channels is unsupported, limiting to first 32\n", ichannels);
146 dsb->mix_channels = 32;
149 else if (ichannels == 1)
151 dsb->mix_channels = 1;
153 if (ochannels == 2)
154 dsb->put = put_mono2stereo;
155 else if (ochannels == 4)
156 dsb->put = put_mono2quad;
157 else if (ochannels == 6)
158 dsb->put = put_mono2surround51;
160 else if (ochannels == 1)
162 dsb->mix_channels = 1;
163 dsb->get = get_mono;
165 else if (ichannels == 2 && ochannels == 4)
167 dsb->mix_channels = 2;
168 dsb->put = put_stereo2quad;
170 else if (ichannels == 2 && ochannels == 6)
172 dsb->mix_channels = 2;
173 dsb->put = put_stereo2surround51;
175 else if (ichannels == 6 && ochannels == 2)
177 dsb->mix_channels = 6;
178 dsb->put = put_surround512stereo;
179 dsb->put_aux = putieee32_sum;
181 else if (ichannels == 8 && ochannels == 2)
183 dsb->mix_channels = 8;
184 dsb->put = put_surround712stereo;
185 dsb->put_aux = putieee32_sum;
187 else if (ichannels == 4 && ochannels == 2)
189 dsb->mix_channels = 4;
190 dsb->put = put_quad2stereo;
191 dsb->put_aux = putieee32_sum;
193 else
195 if (ichannels > 2)
196 FIXME("Conversion from %lu to %lu channels is not implemented, falling back to stereo\n", ichannels, ochannels);
197 dsb->mix_channels = 2;
202 * Check for application callback requests for when the play position
203 * reaches certain points.
205 * The offsets that will be triggered will be those between the recorded
206 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
207 * beyond that position.
209 void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
211 int first, left, right, check;
213 if(dsb->nrofnotifies == 0)
214 return;
216 if(dsb->state == STATE_STOPPED){
217 TRACE("Stopped...\n");
218 /* DSBPN_OFFSETSTOP notifies are always at the start of the sorted array */
219 for(left = 0; left < dsb->nrofnotifies; ++left){
220 if(dsb->notifies[left].dwOffset != DSBPN_OFFSETSTOP)
221 break;
223 TRACE("Signalling %p\n", dsb->notifies[left].hEventNotify);
224 SetEvent(dsb->notifies[left].hEventNotify);
226 return;
229 for(first = 0; first < dsb->nrofnotifies && dsb->notifies[first].dwOffset == DSBPN_OFFSETSTOP; ++first)
232 if(first == dsb->nrofnotifies)
233 return;
235 check = left = first;
236 right = dsb->nrofnotifies - 1;
238 /* find leftmost notify that is greater than playpos */
239 while(left != right){
240 check = left + (right - left) / 2;
241 if(dsb->notifies[check].dwOffset < playpos)
242 left = check + 1;
243 else if(dsb->notifies[check].dwOffset > playpos)
244 right = check;
245 else{
246 left = check;
247 break;
251 TRACE("Not stopped: first notify: %u (%lu), left notify: %u (%lu), range: [%lu,%lu)\n",
252 first, dsb->notifies[first].dwOffset,
253 left, dsb->notifies[left].dwOffset,
254 playpos, (playpos + len) % dsb->buflen);
256 /* send notifications in range */
257 if(dsb->notifies[left].dwOffset >= playpos){
258 for(check = left; check < dsb->nrofnotifies; ++check){
259 if(dsb->notifies[check].dwOffset >= playpos + len)
260 break;
262 TRACE("Signalling %p (%lu)\n", dsb->notifies[check].hEventNotify, dsb->notifies[check].dwOffset);
263 SetEvent(dsb->notifies[check].hEventNotify);
267 if(playpos + len > dsb->buflen){
268 for(check = first; check < left; ++check){
269 if(dsb->notifies[check].dwOffset >= (playpos + len) % dsb->buflen)
270 break;
272 TRACE("Signalling %p (%lu)\n", dsb->notifies[check].hEventNotify, dsb->notifies[check].dwOffset);
273 SetEvent(dsb->notifies[check].hEventNotify);
278 static inline float get_current_sample(const IDirectSoundBufferImpl *dsb,
279 BYTE *buffer, DWORD buflen, DWORD mixpos, DWORD channel)
281 if (mixpos >= buflen && !(dsb->playflags & DSBPLAY_LOOPING))
282 return 0.0f;
283 return dsb->get(dsb, buffer + (mixpos % buflen), channel);
286 static UINT cp_fields_noresample(IDirectSoundBufferImpl *dsb, UINT count)
288 UINT istride = dsb->pwfx->nBlockAlign;
289 UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
290 UINT committed_samples = 0;
291 DWORD channel, i;
293 if (!secondarybuffer_is_audible(dsb))
294 return count;
296 if(dsb->use_committed) {
297 committed_samples = (dsb->writelead - dsb->committed_mixpos) / istride;
298 committed_samples = committed_samples <= count ? committed_samples : count;
301 for (i = 0; i < committed_samples; i++)
302 for (channel = 0; channel < dsb->mix_channels; channel++)
303 dsb->put(dsb, i * ostride, channel, get_current_sample(dsb, dsb->committedbuff,
304 dsb->writelead, dsb->committed_mixpos + i * istride, channel));
306 for (; i < count; i++)
307 for (channel = 0; channel < dsb->mix_channels; channel++)
308 dsb->put(dsb, i * ostride, channel, get_current_sample(dsb, dsb->buffer->memory,
309 dsb->buflen, dsb->sec_mixpos + i * istride, channel));
311 return count;
314 static UINT cp_fields_resample(IDirectSoundBufferImpl *dsb, UINT count, LONG64 *freqAccNum)
316 UINT i, channel;
317 UINT istride = dsb->pwfx->nBlockAlign;
318 UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
319 UINT committed_samples = 0;
321 LONG64 freqAcc_start = *freqAccNum;
322 LONG64 freqAcc_end = freqAcc_start + count * dsb->freqAdjustNum;
323 UINT dsbfirstep = dsb->firstep;
324 UINT channels = dsb->mix_channels;
325 UINT max_ipos = (freqAcc_start + count * dsb->freqAdjustNum) / dsb->freqAdjustDen;
327 UINT fir_cachesize = (fir_len + dsbfirstep - 2) / dsbfirstep;
328 UINT required_input = max_ipos + fir_cachesize;
329 float *intermediate, *fir_copy, *itmp;
331 DWORD len = required_input * channels;
332 len += fir_cachesize;
333 len *= sizeof(float);
335 *freqAccNum = freqAcc_end % dsb->freqAdjustDen;
337 if (!secondarybuffer_is_audible(dsb))
338 return max_ipos;
340 if (!dsb->device->cp_buffer) {
341 dsb->device->cp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
342 dsb->device->cp_buffer_len = len;
343 } else if (len > dsb->device->cp_buffer_len) {
344 dsb->device->cp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->cp_buffer, len);
345 dsb->device->cp_buffer_len = len;
348 fir_copy = dsb->device->cp_buffer;
349 intermediate = fir_copy + fir_cachesize;
351 if(dsb->use_committed) {
352 committed_samples = (dsb->writelead - dsb->committed_mixpos) / istride;
353 committed_samples = committed_samples <= required_input ? committed_samples : required_input;
356 /* Important: this buffer MUST be non-interleaved
357 * if you want -msse3 to have any effect.
358 * This is good for CPU cache effects, too.
360 itmp = intermediate;
361 for (channel = 0; channel < channels; channel++) {
362 for (i = 0; i < committed_samples; i++)
363 *(itmp++) = get_current_sample(dsb, dsb->committedbuff,
364 dsb->writelead, dsb->committed_mixpos + i * istride, channel);
365 for (; i < required_input; i++)
366 *(itmp++) = get_current_sample(dsb, dsb->buffer->memory,
367 dsb->buflen, dsb->sec_mixpos + i * istride, channel);
370 for(i = 0; i < count; ++i) {
371 UINT int_fir_steps = (freqAcc_start + i * dsb->freqAdjustNum) * dsbfirstep / dsb->freqAdjustDen;
372 float total_fir_steps = (freqAcc_start + i * dsb->freqAdjustNum) * dsbfirstep / (float)dsb->freqAdjustDen;
373 UINT ipos = int_fir_steps / dsbfirstep;
375 UINT idx = (ipos + 1) * dsbfirstep - int_fir_steps - 1;
376 float rem = int_fir_steps + 1.0 - total_fir_steps;
378 int fir_used = 0;
379 while (idx < fir_len - 1) {
380 fir_copy[fir_used++] = fir[idx] * (1.0 - rem) + fir[idx + 1] * rem;
381 idx += dsb->firstep;
384 assert(fir_used <= fir_cachesize);
385 assert(ipos + fir_used <= required_input);
387 for (channel = 0; channel < dsb->mix_channels; channel++) {
388 int j;
389 float sum = 0.0;
390 float* cache = &intermediate[channel * required_input + ipos];
391 for (j = 0; j < fir_used; j++)
392 sum += fir_copy[j] * cache[j];
393 dsb->put(dsb, i * ostride, channel, sum * dsb->firgain);
397 return max_ipos;
400 static void cp_fields(IDirectSoundBufferImpl *dsb, UINT count, LONG64 *freqAccNum)
402 DWORD ipos, adv;
404 if (dsb->freqAdjustNum == dsb->freqAdjustDen)
405 adv = cp_fields_noresample(dsb, count); /* *freqAccNum is unmodified */
406 else
407 adv = cp_fields_resample(dsb, count, freqAccNum);
409 ipos = dsb->sec_mixpos + adv * dsb->pwfx->nBlockAlign;
410 if (ipos >= dsb->buflen) {
411 if (dsb->playflags & DSBPLAY_LOOPING)
412 ipos %= dsb->buflen;
413 else {
414 ipos = 0;
415 dsb->state = STATE_STOPPED;
419 dsb->sec_mixpos = ipos;
421 if(dsb->use_committed) {
422 dsb->committed_mixpos += adv * dsb->pwfx->nBlockAlign;
423 if(dsb->committed_mixpos >= dsb->writelead)
424 dsb->use_committed = FALSE;
429 * Calculate the distance between two buffer offsets, taking wraparound
430 * into account.
432 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
434 /* If these asserts fail, the problem is not here, but in the underlying code */
435 assert(ptr1 < buflen);
436 assert(ptr2 < buflen);
437 if (ptr1 >= ptr2) {
438 return ptr1 - ptr2;
439 } else {
440 return buflen + ptr1 - ptr2;
444 * Mix at most the given amount of data into the allocated temporary buffer
445 * of the given secondary buffer, starting from the dsb's first currently
446 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
447 * and bits-per-sample so that it is ideal for the primary buffer.
448 * Doesn't perform any mixing - this is a straight copy/convert operation.
450 * dsb = the secondary buffer
451 * writepos = Starting position of changed buffer
452 * len = number of bytes to resample from writepos
454 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
456 static void DSOUND_MixToTemporary(IDirectSoundBufferImpl *dsb, DWORD frames)
458 UINT size_bytes = frames * sizeof(float) * dsb->device->pwfx->nChannels;
459 HRESULT hr;
460 int i;
462 if (dsb->device->tmp_buffer_len < size_bytes || !dsb->device->tmp_buffer)
464 dsb->device->tmp_buffer_len = size_bytes;
465 if (dsb->device->tmp_buffer)
466 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, size_bytes);
467 else
468 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, 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);
787 while (dev->ref) {
788 DWORD ret;
791 * Some audio drivers are retarded and won't fire after being
792 * stopped, add a timeout to handle this.
794 ret = WaitForSingleObject(dev->sleepev, dev->sleeptime);
795 if (ret == WAIT_FAILED)
796 WARN("wait returned error %lu %08lx!\n", GetLastError(), GetLastError());
797 else if (ret != WAIT_OBJECT_0)
798 WARN("wait returned %08lx!\n", ret);
799 if (!dev->ref)
800 break;
802 AcquireSRWLockShared(&dev->buffer_list_lock);
803 DSOUND_PerformMix(dev);
804 ReleaseSRWLockShared(&dev->buffer_list_lock);
806 return 0;