gdi32: Move the handling of font family fallbacks out of freetype.c.
[wine/zf.git] / dlls / dsound / mixer.c
bloba6402b09eff8318cd8426158e931f8c6fb7f2341
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=%d Pan=%d\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 = %x, right = %x\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=%x, right=%x\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=%d Pan=%d\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 %u 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 %u to %u 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 (%u), left notify: %u (%u), range: [%u,%u)\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 (%u)\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 (%u)\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 DWORD mixpos, DWORD channel)
281 if (mixpos >= dsb->buflen && !(dsb->playflags & DSBPLAY_LOOPING))
282 return 0.0f;
283 return dsb->get(dsb, mixpos % dsb->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 DWORD channel, i;
291 for (i = 0; i < count; i++)
292 for (channel = 0; channel < dsb->mix_channels; channel++)
293 dsb->put(dsb, i * ostride, channel, get_current_sample(dsb,
294 dsb->sec_mixpos + i * istride, channel));
295 return count;
298 static UINT cp_fields_resample(IDirectSoundBufferImpl *dsb, UINT count, LONG64 *freqAccNum)
300 UINT i, channel;
301 UINT istride = dsb->pwfx->nBlockAlign;
302 UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
304 LONG64 freqAcc_start = *freqAccNum;
305 LONG64 freqAcc_end = freqAcc_start + count * dsb->freqAdjustNum;
306 UINT dsbfirstep = dsb->firstep;
307 UINT channels = dsb->mix_channels;
308 UINT max_ipos = (freqAcc_start + count * dsb->freqAdjustNum) / dsb->freqAdjustDen;
310 UINT fir_cachesize = (fir_len + dsbfirstep - 2) / dsbfirstep;
311 UINT required_input = max_ipos + fir_cachesize;
312 float *intermediate, *fir_copy, *itmp;
314 DWORD len = required_input * channels;
315 len += fir_cachesize;
316 len *= sizeof(float);
318 if (!dsb->device->cp_buffer) {
319 dsb->device->cp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
320 dsb->device->cp_buffer_len = len;
321 } else if (len > dsb->device->cp_buffer_len) {
322 dsb->device->cp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->cp_buffer, len);
323 dsb->device->cp_buffer_len = len;
326 fir_copy = dsb->device->cp_buffer;
327 intermediate = fir_copy + fir_cachesize;
330 /* Important: this buffer MUST be non-interleaved
331 * if you want -msse3 to have any effect.
332 * This is good for CPU cache effects, too.
334 itmp = intermediate;
335 for (channel = 0; channel < channels; channel++)
336 for (i = 0; i < required_input; i++)
337 *(itmp++) = get_current_sample(dsb,
338 dsb->sec_mixpos + i * istride, channel);
340 for(i = 0; i < count; ++i) {
341 UINT int_fir_steps = (freqAcc_start + i * dsb->freqAdjustNum) * dsbfirstep / dsb->freqAdjustDen;
342 float total_fir_steps = (freqAcc_start + i * dsb->freqAdjustNum) * dsbfirstep / (float)dsb->freqAdjustDen;
343 UINT ipos = int_fir_steps / dsbfirstep;
345 UINT idx = (ipos + 1) * dsbfirstep - int_fir_steps - 1;
346 float rem = int_fir_steps + 1.0 - total_fir_steps;
348 int fir_used = 0;
349 while (idx < fir_len - 1) {
350 fir_copy[fir_used++] = fir[idx] * (1.0 - rem) + fir[idx + 1] * rem;
351 idx += dsb->firstep;
354 assert(fir_used <= fir_cachesize);
355 assert(ipos + fir_used <= required_input);
357 for (channel = 0; channel < dsb->mix_channels; channel++) {
358 int j;
359 float sum = 0.0;
360 float* cache = &intermediate[channel * required_input + ipos];
361 for (j = 0; j < fir_used; j++)
362 sum += fir_copy[j] * cache[j];
363 dsb->put(dsb, i * ostride, channel, sum * dsb->firgain);
367 *freqAccNum = freqAcc_end % dsb->freqAdjustDen;
369 return max_ipos;
372 static void cp_fields(IDirectSoundBufferImpl *dsb, UINT count, LONG64 *freqAccNum)
374 DWORD ipos, adv;
376 if (dsb->freqAdjustNum == dsb->freqAdjustDen)
377 adv = cp_fields_noresample(dsb, count); /* *freqAccNum is unmodified */
378 else
379 adv = cp_fields_resample(dsb, count, freqAccNum);
381 ipos = dsb->sec_mixpos + adv * dsb->pwfx->nBlockAlign;
382 if (ipos >= dsb->buflen) {
383 if (dsb->playflags & DSBPLAY_LOOPING)
384 ipos %= dsb->buflen;
385 else {
386 ipos = 0;
387 dsb->state = STATE_STOPPED;
391 dsb->sec_mixpos = ipos;
395 * Calculate the distance between two buffer offsets, taking wraparound
396 * into account.
398 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
400 /* If these asserts fail, the problem is not here, but in the underlying code */
401 assert(ptr1 < buflen);
402 assert(ptr2 < buflen);
403 if (ptr1 >= ptr2) {
404 return ptr1 - ptr2;
405 } else {
406 return buflen + ptr1 - ptr2;
410 * Mix at most the given amount of data into the allocated temporary buffer
411 * of the given secondary buffer, starting from the dsb's first currently
412 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
413 * and bits-per-sample so that it is ideal for the primary buffer.
414 * Doesn't perform any mixing - this is a straight copy/convert operation.
416 * dsb = the secondary buffer
417 * writepos = Starting position of changed buffer
418 * len = number of bytes to resample from writepos
420 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
422 static void DSOUND_MixToTemporary(IDirectSoundBufferImpl *dsb, DWORD frames)
424 UINT size_bytes = frames * sizeof(float) * dsb->device->pwfx->nChannels;
425 HRESULT hr;
426 int i;
428 if (dsb->device->tmp_buffer_len < size_bytes || !dsb->device->tmp_buffer)
430 dsb->device->tmp_buffer_len = size_bytes;
431 if (dsb->device->tmp_buffer)
432 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, size_bytes);
433 else
434 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, size_bytes);
436 if(dsb->put_aux == putieee32_sum)
437 memset(dsb->device->tmp_buffer, 0, dsb->device->tmp_buffer_len);
439 cp_fields(dsb, frames, &dsb->freqAccNum);
441 if (size_bytes > 0) {
442 for (i = 0; i < dsb->num_filters; i++) {
443 if (dsb->filters[i].inplace) {
444 hr = IMediaObjectInPlace_Process(dsb->filters[i].inplace, size_bytes, (BYTE*)dsb->device->tmp_buffer, 0, DMO_INPLACE_NORMAL);
446 if (FAILED(hr))
447 WARN("IMediaObjectInPlace_Process failed for filter %u\n", i);
448 } else
449 WARN("filter %u has no inplace object - unsupported\n", i);
454 static void DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT frames)
456 INT i;
457 float vols[DS_MAX_CHANNELS];
458 UINT channels = dsb->device->pwfx->nChannels, chan;
460 TRACE("(%p,%d)\n",dsb,frames);
461 TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalAmpFactor[0],
462 dsb->volpan.dwTotalAmpFactor[1]);
464 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
465 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
466 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
467 return; /* Nothing to do */
469 if (channels > DS_MAX_CHANNELS)
471 FIXME("There is no support for %u channels\n", channels);
472 return;
475 for (i = 0; i < channels; ++i)
476 vols[i] = dsb->volpan.dwTotalAmpFactor[i] / ((float)0xFFFF);
478 for(i = 0; i < frames; ++i){
479 for(chan = 0; chan < channels; ++chan){
480 dsb->device->tmp_buffer[i * channels + chan] *= vols[chan];
486 * Mix (at most) the given number of bytes into the given position of the
487 * device buffer, from the secondary buffer "dsb" (starting at the current
488 * mix position for that buffer).
490 * Returns the number of bytes actually mixed into the device buffer. This
491 * will match fraglen unless the end of the secondary buffer is reached
492 * (and it is not looping).
494 * dsb = the secondary buffer to mix from
495 * fraglen = number of bytes to mix
497 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, float *mix_buffer, DWORD frames)
499 float *ibuf;
500 DWORD oldpos;
502 TRACE("sec_mixpos=%d/%d\n", dsb->sec_mixpos, dsb->buflen);
503 TRACE("(%p, frames=%d)\n",dsb,frames);
505 /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
506 oldpos = dsb->sec_mixpos;
507 DSOUND_MixToTemporary(dsb, frames);
508 ibuf = dsb->device->tmp_buffer;
510 /* Apply volume if needed */
511 DSOUND_MixerVol(dsb, frames);
513 mixieee32(ibuf, mix_buffer, frames * dsb->device->pwfx->nChannels);
515 /* check for notification positions */
516 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
517 dsb->state != STATE_STARTING) {
518 INT ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
519 DSOUND_CheckEvent(dsb, oldpos, ilen);
522 return frames;
526 * Mix some frames from the given secondary buffer "dsb" into the device
527 * primary buffer.
529 * dsb = the secondary buffer
530 * playpos = the current play position in the device buffer (primary buffer)
531 * frames = the maximum number of frames in the primary buffer to mix, from the
532 * current writepos.
534 * Returns: the number of frames beyond the writepos that were mixed.
536 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, float *mix_buffer, DWORD frames)
538 DWORD primary_done = 0;
540 TRACE("(%p, frames=%d)\n",dsb,frames);
541 TRACE("looping=%d, leadin=%d\n", dsb->playflags, dsb->leadin);
543 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
544 /* FIXME: Is this needed? */
545 if (dsb->leadin && dsb->state == STATE_STARTING) {
546 if (frames > 2 * dsb->device->frag_frames) {
547 primary_done = frames - 2 * dsb->device->frag_frames;
548 frames = 2 * dsb->device->frag_frames;
549 dsb->sec_mixpos += primary_done *
550 dsb->pwfx->nBlockAlign * dsb->freqAdjustNum / dsb->freqAdjustDen;
554 dsb->leadin = FALSE;
556 TRACE("frames (primary) = %i\n", frames);
558 /* First try to mix to the end of the buffer if possible
559 * Theoretically it would allow for better optimization
561 primary_done += DSOUND_MixInBuffer(dsb, mix_buffer, frames);
563 TRACE("total mixed data=%d\n", primary_done);
565 /* Report back the total prebuffered amount for this buffer */
566 return primary_done;
570 * For a DirectSoundDevice, go through all the currently playing buffers and
571 * mix them in to the device buffer.
573 * frames = the maximum amount to mix into the primary buffer
574 * all_stopped = reports back if all buffers have stopped
576 * Returns: the length beyond the writepos that was mixed to.
579 static void DSOUND_MixToPrimary(const DirectSoundDevice *device, float *mix_buffer, DWORD frames, BOOL *all_stopped)
581 INT i;
582 IDirectSoundBufferImpl *dsb;
584 /* unless we find a running buffer, all have stopped */
585 *all_stopped = TRUE;
587 TRACE("(frames %d)\n", frames);
588 for (i = 0; i < device->nrofbuffers; i++) {
589 dsb = device->buffers[i];
591 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
593 if (dsb->buflen && dsb->state) {
594 TRACE("Checking %p, frames=%d\n", dsb, frames);
595 AcquireSRWLockShared(&dsb->lock);
596 /* if buffer is stopping it is stopped now */
597 if (dsb->state == STATE_STOPPING) {
598 dsb->state = STATE_STOPPED;
599 DSOUND_CheckEvent(dsb, 0, 0);
600 } else if (dsb->state != STATE_STOPPED) {
602 /* if the buffer was starting, it must be playing now */
603 if (dsb->state == STATE_STARTING)
604 dsb->state = STATE_PLAYING;
606 /* mix next buffer into the main buffer */
607 DSOUND_MixOne(dsb, mix_buffer, frames);
609 *all_stopped = FALSE;
611 ReleaseSRWLockShared(&dsb->lock);
617 * Add buffers to the emulated wave device system.
619 * device = The current dsound playback device
620 * force = If TRUE, the function will buffer up as many frags as possible,
621 * even though and will ignore the actual state of the primary buffer.
623 * Returns: None
626 static void DSOUND_WaveQueue(DirectSoundDevice *device, LPBYTE pos, DWORD bytes)
628 BYTE *buffer;
629 HRESULT hr;
631 TRACE("(%p)\n", device);
633 hr = IAudioRenderClient_GetBuffer(device->render, bytes / device->pwfx->nBlockAlign, &buffer);
634 if(FAILED(hr)){
635 WARN("GetBuffer failed: %08x\n", hr);
636 return;
639 memcpy(buffer, pos, bytes);
641 hr = IAudioRenderClient_ReleaseBuffer(device->render, bytes / device->pwfx->nBlockAlign, 0);
642 if(FAILED(hr)) {
643 ERR("ReleaseBuffer failed: %08x\n", hr);
644 IAudioRenderClient_ReleaseBuffer(device->render, 0, 0);
645 return;
648 device->pad += bytes;
652 * Perform mixing for a Direct Sound device. That is, go through all the
653 * secondary buffers (the sound bites currently playing) and mix them in
654 * to the primary buffer (the device buffer).
656 * The mixing procedure goes:
658 * secondary->buffer (secondary format)
659 * =[Resample]=> device->tmp_buffer (float format)
660 * =[Volume]=> device->tmp_buffer (float format)
661 * =[Reformat]=> device->buffer (device format, skipped on float)
663 static void DSOUND_PerformMix(DirectSoundDevice *device)
665 DWORD block, pad_frames, pad_bytes, frames;
666 HRESULT hr;
668 TRACE("(%p)\n", device);
670 /* **** */
671 EnterCriticalSection(&device->mixlock);
673 hr = IAudioClient_GetCurrentPadding(device->client, &pad_frames);
674 if(FAILED(hr)){
675 WARN("GetCurrentPadding failed: %08x\n", hr);
676 LeaveCriticalSection(&device->mixlock);
677 return;
679 block = device->pwfx->nBlockAlign;
680 pad_bytes = pad_frames * block;
681 device->playpos += device->pad - pad_bytes;
682 device->playpos %= device->buflen;
683 device->pad = pad_bytes;
685 frames = device->ac_frames - pad_frames;
686 if(!frames){
687 /* nothing to do! */
688 LeaveCriticalSection(&device->mixlock);
689 return;
691 if (frames > device->frag_frames * 3)
692 frames = device->frag_frames * 3;
694 if (device->priolevel != DSSCL_WRITEPRIMARY) {
695 BOOL all_stopped = FALSE;
696 int nfiller;
697 void *buffer = NULL;
699 /* the sound of silence */
700 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
702 /* check for underrun. underrun occurs when the write position passes the mix position
703 * also wipe out just-played sound data */
704 if (!pad_frames)
705 WARN("Probable buffer underrun\n");
707 hr = IAudioRenderClient_GetBuffer(device->render, frames, (BYTE **)&buffer);
708 if(FAILED(hr)){
709 WARN("GetBuffer failed: %08x\n", hr);
710 LeaveCriticalSection(&device->mixlock);
711 return;
714 memset(buffer, nfiller, frames * block);
716 if (!device->normfunction)
717 DSOUND_MixToPrimary(device, buffer, frames, &all_stopped);
718 else {
719 memset(device->buffer, nfiller, device->buflen);
721 /* do the mixing */
722 DSOUND_MixToPrimary(device, (float*)device->buffer, frames, &all_stopped);
724 device->normfunction(device->buffer, buffer, frames * device->pwfx->nChannels);
727 hr = IAudioRenderClient_ReleaseBuffer(device->render, frames, 0);
728 if(FAILED(hr))
729 ERR("ReleaseBuffer failed: %08x\n", hr);
731 device->pad += frames * block;
732 } else if (!device->stopped) {
733 DWORD writepos = (device->playpos + pad_bytes) % device->buflen;
734 DWORD bytes = frames * block;
736 if (bytes > device->buflen)
737 bytes = device->buflen;
738 if (writepos + bytes > device->buflen) {
739 DSOUND_WaveQueue(device, device->buffer + writepos, device->buflen - writepos);
740 DSOUND_WaveQueue(device, device->buffer, writepos + bytes - device->buflen);
741 } else
742 DSOUND_WaveQueue(device, device->buffer + writepos, bytes);
745 LeaveCriticalSection(&(device->mixlock));
746 /* **** */
749 DWORD CALLBACK DSOUND_mixthread(void *p)
751 DirectSoundDevice *dev = p;
752 TRACE("(%p)\n", dev);
754 while (dev->ref) {
755 DWORD ret;
758 * Some audio drivers are retarded and won't fire after being
759 * stopped, add a timeout to handle this.
761 ret = WaitForSingleObject(dev->sleepev, dev->sleeptime);
762 if (ret == WAIT_FAILED)
763 WARN("wait returned error %u %08x!\n", GetLastError(), GetLastError());
764 else if (ret != WAIT_OBJECT_0)
765 WARN("wait returned %08x!\n", ret);
766 if (!dev->ref)
767 break;
769 AcquireSRWLockShared(&dev->buffer_list_lock);
770 DSOUND_PerformMix(dev);
771 ReleaseSRWLockShared(&dev->buffer_list_lock);
773 return 0;