dsound-fixup-loop
[wine/multimedia.git] / dlls / dsound / mixer.c
blobb3aa1d1949ecb92adeddbf688e76512d5fed1716
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
30 #define NONAMELESSSTRUCT
31 #define NONAMELESSUNION
32 #include "windef.h"
33 #include "winbase.h"
34 #include "mmsystem.h"
35 #include "wingdi.h"
36 #include "mmreg.h"
37 #include "winternl.h"
38 #include "wine/debug.h"
39 #include "dsound.h"
40 #include "ks.h"
41 #include "ksmedia.h"
42 #include "dsound_private.h"
43 #include "fir.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
47 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
49 double temp;
50 TRACE("(%p)\n",volpan);
52 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
53 /* the AmpFactors are expressed in 16.16 fixed point */
54 volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
55 /* FIXME: dwPan{Left|Right}AmpFactor */
57 /* FIXME: use calculated vol and pan ampfactors */
58 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
59 volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
60 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
61 volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
63 TRACE("left = %x, right = %x\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
66 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
68 double left,right;
69 TRACE("(%p)\n",volpan);
71 TRACE("left=%x, right=%x\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
72 if (volpan->dwTotalLeftAmpFactor==0)
73 left=-10000;
74 else
75 left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
76 if (volpan->dwTotalRightAmpFactor==0)
77 right=-10000;
78 else
79 right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
80 if (left<right)
82 volpan->lVolume=right;
83 volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
85 else
87 volpan->lVolume=left;
88 volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
90 if (volpan->lVolume < -10000)
91 volpan->lVolume=-10000;
92 volpan->lPan=right-left;
93 if (volpan->lPan < -10000)
94 volpan->lPan=-10000;
96 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
99 /**
100 * Recalculate the size for temporary buffer, and new writelead
101 * Should be called when one of the following things occur:
102 * - Primary buffer format is changed
103 * - This buffer format (frequency) is changed
105 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
107 DWORD ichannels = dsb->pwfx->nChannels;
108 DWORD ochannels = dsb->device->pwfx->nChannels;
109 WAVEFORMATEXTENSIBLE *pwfxe;
110 BOOL ieee = FALSE;
112 TRACE("(%p)\n",dsb);
114 pwfxe = (WAVEFORMATEXTENSIBLE *) dsb->pwfx;
115 dsb->freqAdjust = (float)dsb->freq / dsb->device->pwfx->nSamplesPerSec;
117 if ((pwfxe->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) || ((pwfxe->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
118 && (IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))))
119 ieee = TRUE;
122 * Recalculate FIR step and gain.
124 * firstep says how many points of the FIR exist per one
125 * sample in the secondary buffer. firgain specifies what
126 * to multiply the FIR output by in order to attenuate it correctly.
128 if (dsb->freqAdjust > 1.0f) {
130 * Yes, round it a bit to make sure that the
131 * linear interpolation factor never changes.
133 dsb->firstep = ceil(fir_step / dsb->freqAdjust);
134 } else {
135 dsb->firstep = fir_step;
137 dsb->firgain = (float)dsb->firstep / fir_step;
139 /* calculate the 10ms write lead */
140 dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
142 dsb->freqAcc = 0;
144 dsb->get_aux = ieee ? getbpp[4] : getbpp[dsb->pwfx->wBitsPerSample/8 - 1];
145 dsb->put_aux = putieee32;
147 dsb->get = dsb->get_aux;
148 dsb->put = dsb->put_aux;
150 if (ichannels == ochannels)
152 dsb->mix_channels = ichannels;
153 if (ichannels > 32) {
154 FIXME("Copying %u channels is unsupported, limiting to first 32\n", ichannels);
155 dsb->mix_channels = 32;
158 else if (ichannels == 1)
160 dsb->mix_channels = 1;
161 dsb->put = put_mono2stereo;
163 else if (ochannels == 1)
165 dsb->mix_channels = 1;
166 dsb->get = get_mono;
168 else
170 if (ichannels > 2)
171 FIXME("Conversion from %u to %u channels is not implemented, falling back to stereo\n", ichannels, ochannels);
172 dsb->mix_channels = 2;
177 * Check for application callback requests for when the play position
178 * reaches certain points.
180 * The offsets that will be triggered will be those between the recorded
181 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
182 * beyond that position.
184 void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
186 int i;
187 DWORD offset;
188 LPDSBPOSITIONNOTIFY event;
189 TRACE("(%p,%d)\n",dsb,len);
191 if (dsb->nrofnotifies == 0)
192 return;
194 TRACE("(%p) buflen = %d, playpos = %d, len = %d\n",
195 dsb, dsb->buflen, playpos, len);
196 for (i = 0; i < dsb->nrofnotifies ; i++) {
197 event = dsb->notifies + i;
198 offset = event->dwOffset;
199 TRACE("checking %d, position %d, event = %p\n",
200 i, offset, event->hEventNotify);
201 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
202 /* OK. [Inside DirectX, p274] */
203 /* Windows does not seem to enforce this, and some apps rely */
204 /* on that, so we can't stop there. */
205 /* */
206 /* This also means we can't sort the entries by offset, */
207 /* because DSBPN_OFFSETSTOP == -1 */
208 if (offset == DSBPN_OFFSETSTOP) {
209 if (dsb->state == STATE_STOPPED) {
210 SetEvent(event->hEventNotify);
211 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
213 continue;
215 if ((playpos + len) >= dsb->buflen) {
216 if ((offset < ((playpos + len) % dsb->buflen)) ||
217 (offset >= playpos)) {
218 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
219 SetEvent(event->hEventNotify);
221 } else {
222 if ((offset >= playpos) && (offset < (playpos + len))) {
223 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
224 SetEvent(event->hEventNotify);
230 static inline float get_current_sample(const IDirectSoundBufferImpl *dsb,
231 DWORD mixpos, DWORD channel)
233 if (mixpos >= dsb->buflen && !(dsb->playflags & DSBPLAY_LOOPING))
234 return 0.0f;
235 return dsb->get(dsb, mixpos % dsb->buflen, channel);
238 static UINT cp_fields_noresample(IDirectSoundBufferImpl *dsb, UINT count)
240 UINT istride = dsb->pwfx->nBlockAlign;
241 UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
242 DWORD channel, i;
243 for (i = 0; i < count; i++)
244 for (channel = 0; channel < dsb->mix_channels; channel++)
245 dsb->put(dsb, i * ostride, channel, get_current_sample(dsb,
246 dsb->sec_mixpos + i * istride, channel));
247 return count;
250 static UINT cp_fields_resample(IDirectSoundBufferImpl *dsb, UINT count, float *freqAcc)
252 UINT i, channel;
253 UINT istride = dsb->pwfx->nBlockAlign;
254 UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
256 float freqAdjust = dsb->freqAdjust;
257 float freqAcc_start = *freqAcc;
258 float freqAcc_end = freqAcc_start + count * freqAdjust;
259 UINT dsbfirstep = dsb->firstep;
260 UINT channels = dsb->mix_channels;
261 UINT max_ipos = freqAcc_start + count * freqAdjust;
263 UINT fir_cachesize = (fir_len + dsbfirstep - 2) / dsbfirstep;
264 UINT required_input = max_ipos + fir_cachesize;
266 float* intermediate = HeapAlloc(GetProcessHeap(), 0,
267 sizeof(float) * required_input * channels);
269 float* fir_copy = HeapAlloc(GetProcessHeap(), 0,
270 sizeof(float) * fir_cachesize);
272 /* Important: this buffer MUST be non-interleaved
273 * if you want -msse3 to have any effect.
274 * This is good for CPU cache effects, too.
276 float* itmp = intermediate;
277 for (channel = 0; channel < channels; channel++)
278 for (i = 0; i < required_input; i++)
279 *(itmp++) = get_current_sample(dsb,
280 dsb->sec_mixpos + i * istride, channel);
282 for(i = 0; i < count; ++i) {
283 float total_fir_steps = (freqAcc_start + i * freqAdjust) * dsbfirstep;
284 UINT int_fir_steps = total_fir_steps;
285 UINT ipos = int_fir_steps / dsbfirstep;
287 UINT idx = (ipos + 1) * dsbfirstep - int_fir_steps - 1;
288 float rem = int_fir_steps + 1.0 - total_fir_steps;
290 int fir_used = 0;
291 while (idx < fir_len - 1) {
292 fir_copy[fir_used++] = fir[idx] * (1.0 - rem) + fir[idx + 1] * rem;
293 idx += dsb->firstep;
296 assert(fir_used <= fir_cachesize);
297 assert(ipos + fir_used <= required_input);
299 for (channel = 0; channel < dsb->mix_channels; channel++) {
300 int j;
301 float sum = 0.0;
302 float* cache = &intermediate[channel * required_input + ipos];
303 for (j = 0; j < fir_used; j++)
304 sum += fir_copy[j] * cache[j];
305 dsb->put(dsb, i * ostride, channel, sum * dsb->firgain);
309 freqAcc_end -= (int)freqAcc_end;
310 *freqAcc = freqAcc_end;
312 HeapFree(GetProcessHeap(), 0, fir_copy);
313 HeapFree(GetProcessHeap(), 0, intermediate);
315 return max_ipos;
318 static void cp_fields(IDirectSoundBufferImpl *dsb, UINT count, float *freqAcc)
320 DWORD ipos, adv;
322 if (dsb->freqAdjust == 1.0)
323 adv = cp_fields_noresample(dsb, count); /* *freqAcc is unmodified */
324 else
325 adv = cp_fields_resample(dsb, count, freqAcc);
327 ipos = dsb->sec_mixpos + adv * dsb->pwfx->nBlockAlign;
328 if (ipos >= dsb->buflen) {
329 if (dsb->playflags & DSBPLAY_LOOPING)
330 ipos %= dsb->buflen;
331 else {
332 ipos = 0;
333 dsb->state = STATE_STOPPED;
337 dsb->sec_mixpos = ipos;
341 * Calculate the distance between two buffer offsets, taking wraparound
342 * into account.
344 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
346 /* If these asserts fail, the problem is not here, but in the underlying code */
347 assert(ptr1 < buflen);
348 assert(ptr2 < buflen);
349 if (ptr1 >= ptr2) {
350 return ptr1 - ptr2;
351 } else {
352 return buflen + ptr1 - ptr2;
356 * Mix at most the given amount of data into the allocated temporary buffer
357 * of the given secondary buffer, starting from the dsb's first currently
358 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
359 * and bits-per-sample so that it is ideal for the primary buffer.
360 * Doesn't perform any mixing - this is a straight copy/convert operation.
362 * dsb = the secondary buffer
363 * writepos = Starting position of changed buffer
364 * len = number of bytes to resample from writepos
366 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
368 static void DSOUND_MixToTemporary(IDirectSoundBufferImpl *dsb, DWORD frames)
370 UINT size_bytes = frames * sizeof(float) * dsb->device->pwfx->nChannels;
372 if (dsb->device->tmp_buffer_len < size_bytes || !dsb->device->tmp_buffer)
374 dsb->device->tmp_buffer_len = size_bytes;
375 if (dsb->device->tmp_buffer)
376 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, size_bytes);
377 else
378 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, size_bytes);
381 cp_fields(dsb, frames, &dsb->freqAcc);
384 static void DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT frames)
386 INT i;
387 float vLeft, vRight;
388 UINT channels = dsb->device->pwfx->nChannels, chan;
390 TRACE("(%p,%d)\n",dsb,frames);
391 TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalLeftAmpFactor,
392 dsb->volpan.dwTotalRightAmpFactor);
394 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
395 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
396 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
397 return; /* Nothing to do */
399 if (channels != 1 && channels != 2)
401 FIXME("There is no support for %u channels\n", channels);
402 return;
405 vLeft = dsb->volpan.dwTotalLeftAmpFactor / ((float)0xFFFF);
406 vRight = dsb->volpan.dwTotalRightAmpFactor / ((float)0xFFFF);
407 for(i = 0; i < frames; ++i){
408 for(chan = 0; chan < channels; ++chan){
409 if(chan == 0)
410 dsb->device->tmp_buffer[i * channels + chan] *= vLeft;
411 else
412 dsb->device->tmp_buffer[i * channels + chan] *= vRight;
418 * Mix (at most) the given number of bytes into the given position of the
419 * device buffer, from the secondary buffer "dsb" (starting at the current
420 * mix position for that buffer).
422 * Returns the number of bytes actually mixed into the device buffer. This
423 * will match fraglen unless the end of the secondary buffer is reached
424 * (and it is not looping).
426 * dsb = the secondary buffer to mix from
427 * writepos = position (offset) in device buffer to write at
428 * fraglen = number of bytes to mix
430 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
432 INT len = fraglen;
433 float *ibuf;
434 DWORD oldpos;
435 UINT frames = fraglen / dsb->device->pwfx->nBlockAlign;
437 TRACE("sec_mixpos=%d/%d\n", dsb->sec_mixpos, dsb->buflen);
438 TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
440 if (len % dsb->device->pwfx->nBlockAlign) {
441 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
442 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
443 len -= len % nBlockAlign; /* data alignment */
446 /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
447 oldpos = dsb->sec_mixpos;
449 DSOUND_MixToTemporary(dsb, frames);
450 ibuf = dsb->device->tmp_buffer;
452 /* Apply volume if needed */
453 DSOUND_MixerVol(dsb, frames);
455 mixieee32(ibuf, dsb->device->mix_buffer, frames * dsb->device->pwfx->nChannels);
457 /* check for notification positions */
458 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
459 dsb->state != STATE_STARTING) {
460 INT ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
461 DSOUND_CheckEvent(dsb, oldpos, ilen);
464 return len;
468 * Mix some frames from the given secondary buffer "dsb" into the device
469 * primary buffer.
471 * dsb = the secondary buffer
472 * playpos = the current play position in the device buffer (primary buffer)
473 * writepos = the current safe-to-write position in the device buffer
474 * mixlen = the maximum number of bytes in the primary buffer to mix, from the
475 * current writepos.
477 * Returns: the number of bytes beyond the writepos that were mixed.
479 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD mixlen)
481 DWORD primary_done = 0;
483 TRACE("(%p,%d,%d)\n",dsb,writepos,mixlen);
484 TRACE("writepos=%d, mixlen=%d\n", writepos, mixlen);
485 TRACE("looping=%d, leadin=%d\n", dsb->playflags, dsb->leadin);
487 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
488 /* FIXME: Is this needed? */
489 if (dsb->leadin && dsb->state == STATE_STARTING) {
490 if (mixlen > 2 * dsb->device->fraglen) {
491 primary_done = mixlen - 2 * dsb->device->fraglen;
492 mixlen = 2 * dsb->device->fraglen;
493 writepos += primary_done;
494 dsb->sec_mixpos += (primary_done / dsb->device->pwfx->nBlockAlign) *
495 dsb->pwfx->nBlockAlign * dsb->freqAdjust;
499 dsb->leadin = FALSE;
501 TRACE("mixlen (primary) = %i\n", mixlen);
503 /* First try to mix to the end of the buffer if possible
504 * Theoretically it would allow for better optimization
506 primary_done += DSOUND_MixInBuffer(dsb, writepos, mixlen);
508 TRACE("total mixed data=%d\n", primary_done);
510 /* Report back the total prebuffered amount for this buffer */
511 return primary_done;
515 * For a DirectSoundDevice, go through all the currently playing buffers and
516 * mix them in to the device buffer.
518 * writepos = the current safe-to-write position in the primary buffer
519 * mixlen = the maximum amount to mix into the primary buffer
520 * (beyond the current writepos)
521 * all_stopped = reports back if all buffers have stopped
523 * Returns: the length beyond the writepos that was mixed to.
526 static void DSOUND_MixToPrimary(const DirectSoundDevice *device, DWORD writepos, DWORD mixlen, BOOL *all_stopped)
528 INT i;
529 IDirectSoundBufferImpl *dsb;
531 /* unless we find a running buffer, all have stopped */
532 *all_stopped = TRUE;
534 TRACE("(%d,%d)\n", writepos, mixlen);
535 for (i = 0; i < device->nrofbuffers; i++) {
536 dsb = device->buffers[i];
538 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
540 if (dsb->buflen && dsb->state) {
541 TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
542 RtlAcquireResourceShared(&dsb->lock, TRUE);
543 /* if buffer is stopping it is stopped now */
544 if (dsb->state == STATE_STOPPING) {
545 dsb->state = STATE_STOPPED;
546 DSOUND_CheckEvent(dsb, 0, 0);
547 } else if (dsb->state != STATE_STOPPED) {
549 /* if the buffer was starting, it must be playing now */
550 if (dsb->state == STATE_STARTING)
551 dsb->state = STATE_PLAYING;
553 /* mix next buffer into the main buffer */
554 DSOUND_MixOne(dsb, writepos, mixlen);
556 *all_stopped = FALSE;
558 RtlReleaseResource(&dsb->lock);
564 * Add buffers to the emulated wave device system.
566 * device = The current dsound playback device
567 * force = If TRUE, the function will buffer up as many frags as possible,
568 * even though and will ignore the actual state of the primary buffer.
570 * Returns: None
573 static void DSOUND_WaveQueue(DirectSoundDevice *device, LPBYTE pos, DWORD bytes)
575 BYTE *buffer;
576 HRESULT hr;
578 TRACE("(%p)\n", device);
580 hr = IAudioRenderClient_GetBuffer(device->render, bytes / device->pwfx->nBlockAlign, &buffer);
581 if(FAILED(hr)){
582 WARN("GetBuffer failed: %08x\n", hr);
583 goto done;
586 memcpy(buffer, pos, bytes);
588 hr = IAudioRenderClient_ReleaseBuffer(device->render, bytes / device->pwfx->nBlockAlign, 0);
589 if(FAILED(hr))
590 WARN("ReleaseBuffer failed: %08x\n", hr);
592 done:
593 device->pad += bytes;
597 * Perform mixing for a Direct Sound device. That is, go through all the
598 * secondary buffers (the sound bites currently playing) and mix them in
599 * to the primary buffer (the device buffer).
601 * The mixing procedure goes:
603 * secondary->buffer (secondary format)
604 * =[Resample]=> device->tmp_buffer (float format)
605 * =[Volume]=> device->tmp_buffer (float format)
606 * =[Mix]=> device->mix_buffer (float format)
607 * =[Reformat]=> device->buffer (device format)
609 static void DSOUND_PerformMix(DirectSoundDevice *device)
611 UINT32 pad, maxq;
612 HRESULT hr;
614 TRACE("(%p)\n", device);
616 /* **** */
617 EnterCriticalSection(&device->mixlock);
619 hr = IAudioClient_GetCurrentPadding(device->client, &pad);
620 if(FAILED(hr)){
621 WARN("GetCurrentPadding failed: %08x\n", hr);
622 LeaveCriticalSection(&device->mixlock);
623 return;
625 pad *= device->pwfx->nBlockAlign;
626 device->playpos += device->pad - pad;
627 device->playpos %= device->buflen;
628 device->pad = pad;
630 maxq = device->aclen - pad;
631 if(!maxq){
632 /* nothing to do! */
633 LeaveCriticalSection(&device->mixlock);
634 return;
637 if (device->priolevel != DSSCL_WRITEPRIMARY) {
638 BOOL all_stopped = FALSE;
639 DWORD playpos, writepos;
640 int nfiller;
641 BOOL native = device->normfunction == normfunctions[4];
642 DWORD block = device->pwfx->nBlockAlign;
643 DWORD bpp = device->pwfx->wBitsPerSample>>3;
645 /* the sound of silence */
646 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
648 /* get the position in the primary buffer */
649 if (DSOUND_PrimaryGetPosition(device, &playpos, &writepos) != 0){
650 LeaveCriticalSection(&(device->mixlock));
651 return;
654 assert(device->playpos < device->buflen);
656 /* check for underrun. underrun occurs when the write position passes the mix position
657 * also wipe out just-played sound data */
658 if (!pad)
659 WARN("Probable buffer underrun\n");
660 else if (device->state == STATE_STOPPED ||
661 device->state == STATE_STARTING) {
662 TRACE("Buffer restarting\n");
665 if (native) {
666 void *buffer = NULL, *old = device->mix_buffer;
667 if (maxq > device->fraglen * 3)
668 maxq = device->fraglen * 3;
670 hr = IAudioRenderClient_GetBuffer(device->render, maxq / block, (void*)&buffer);
671 if(FAILED(hr)){
672 WARN("GetBuffer failed: %08x\n", hr);
673 LeaveCriticalSection(&device->mixlock);
674 return;
676 ZeroMemory(buffer, maxq);
678 device->mix_buffer = buffer;
679 DSOUND_MixToPrimary(device, writepos, maxq, &all_stopped);
680 device->mix_buffer = old;
682 hr = IAudioRenderClient_ReleaseBuffer(device->render, maxq / block, 0);
683 if(FAILED(hr))
684 ERR("ReleaseBuffer failed: %08x\n", hr);
686 device->pad += maxq;
687 } else {
688 if (maxq > device->buflen)
689 maxq = device->buflen;
690 ZeroMemory(device->mix_buffer, maxq);
692 /* do the mixing */
693 DSOUND_MixToPrimary(device, writepos, maxq, &all_stopped);
695 if (maxq + writepos > device->buflen) {
696 DWORD todo = device->buflen - writepos;
698 device->normfunction(device->mix_buffer, device->buffer + writepos, todo);
699 DSOUND_WaveQueue(device, device->buffer + writepos, todo);
701 device->normfunction(device->mix_buffer + todo / bpp, device->buffer, (maxq - todo));
702 DSOUND_WaveQueue(device, device->buffer, maxq - todo);
703 } else {
704 device->normfunction(device->mix_buffer, device->buffer + writepos, maxq);
705 DSOUND_WaveQueue(device, device->buffer + writepos, maxq);
709 if (maxq) {
710 if (device->state == STATE_STARTING ||
711 device->state == STATE_STOPPED) {
712 if(DSOUND_PrimaryPlay(device) != DS_OK)
713 WARN("DSOUND_PrimaryPlay failed\n");
714 else if (device->state == STATE_STARTING)
715 device->state = STATE_PLAYING;
716 else
717 device->state = STATE_STOPPING;
719 } else if (!pad && !maxq && (all_stopped == TRUE) &&
720 (device->state == STATE_STOPPING)) {
721 device->state = STATE_STOPPED;
722 DSOUND_PrimaryStop(device);
724 } else {
725 DWORD pos = device->playpos + device->pad;
726 pos %= device->buflen;
728 DSOUND_WaveQueue(device, device->buffer + pos, maxq);
730 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
731 if (device->state == STATE_STARTING) {
732 if (DSOUND_PrimaryPlay(device) != DS_OK)
733 WARN("DSOUND_PrimaryPlay failed\n");
734 else
735 device->state = STATE_PLAYING;
737 else if (device->state == STATE_STOPPING) {
738 if (DSOUND_PrimaryStop(device) != DS_OK)
739 WARN("DSOUND_PrimaryStop failed\n");
740 else
741 device->state = STATE_STOPPED;
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;
757 /* ALSA is retarded, add a timeout.. */
758 ret = WaitForSingleObject(dev->sleepev, 25);
759 if (ret == WAIT_FAILED)
760 WARN("wait returned error %u %08x!\n", GetLastError(), GetLastError());
761 else if (ret)
762 WARN("wait returned %08x!\n", ret);
763 if (!dev->ref)
764 break;
766 RtlAcquireResourceShared(&(dev->buffer_list_lock), TRUE);
767 DSOUND_PerformMix(dev);
768 RtlReleaseResource(&(dev->buffer_list_lock));
770 return 0;