wrc: Declare the data buffer as unsigned char.
[wine.git] / dlls / dsound / mixer.c
blob8d6b379a9fe8061631354430899c2fe95666d6b4
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 first, left, right, check;
188 if(dsb->nrofnotifies == 0)
189 return;
191 if(dsb->state == STATE_STOPPED){
192 TRACE("Stopped...\n");
193 /* DSBPN_OFFSETSTOP notifies are always at the start of the sorted array */
194 for(left = 0; left < dsb->nrofnotifies; ++left){
195 if(dsb->notifies[left].dwOffset != DSBPN_OFFSETSTOP)
196 break;
198 TRACE("Signalling %p\n", dsb->notifies[left].hEventNotify);
199 SetEvent(dsb->notifies[left].hEventNotify);
201 return;
204 for(first = 0; first < dsb->nrofnotifies && dsb->notifies[first].dwOffset == DSBPN_OFFSETSTOP; ++first)
207 if(first == dsb->nrofnotifies)
208 return;
210 check = left = first;
211 right = dsb->nrofnotifies - 1;
213 /* find leftmost notify that is greater than playpos */
214 while(left != right){
215 check = left + (right - left) / 2;
216 if(dsb->notifies[check].dwOffset < playpos)
217 left = check + 1;
218 else if(dsb->notifies[check].dwOffset > playpos)
219 right = check;
220 else{
221 left = check;
222 break;
226 TRACE("Not stopped: first notify: %u (%u), range: [%u,%u)\n", first,
227 dsb->notifies[check].dwOffset, playpos, (playpos + len) % dsb->buflen);
229 /* send notifications in range */
230 for(check = left; check < dsb->nrofnotifies; ++check){
231 if(dsb->notifies[check].dwOffset >= playpos + len)
232 break;
234 TRACE("Signalling %p (%u)\n", dsb->notifies[check].hEventNotify, dsb->notifies[check].dwOffset);
235 SetEvent(dsb->notifies[check].hEventNotify);
238 if(playpos + len > dsb->buflen){
239 for(check = first; check < left; ++check){
240 if(dsb->notifies[check].dwOffset >= (playpos + len) % dsb->buflen)
241 break;
243 TRACE("Signalling %p (%u)\n", dsb->notifies[check].hEventNotify, dsb->notifies[check].dwOffset);
244 SetEvent(dsb->notifies[check].hEventNotify);
249 static inline float get_current_sample(const IDirectSoundBufferImpl *dsb,
250 DWORD mixpos, DWORD channel)
252 if (mixpos >= dsb->buflen && !(dsb->playflags & DSBPLAY_LOOPING))
253 return 0.0f;
254 return dsb->get(dsb, mixpos % dsb->buflen, channel);
257 static UINT cp_fields_noresample(IDirectSoundBufferImpl *dsb, UINT count)
259 UINT istride = dsb->pwfx->nBlockAlign;
260 UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
261 DWORD channel, i;
262 for (i = 0; i < count; i++)
263 for (channel = 0; channel < dsb->mix_channels; channel++)
264 dsb->put(dsb, i * ostride, channel, get_current_sample(dsb,
265 dsb->sec_mixpos + i * istride, channel));
266 return count;
269 static UINT cp_fields_resample(IDirectSoundBufferImpl *dsb, UINT count, float *freqAcc)
271 UINT i, channel;
272 UINT istride = dsb->pwfx->nBlockAlign;
273 UINT ostride = dsb->device->pwfx->nChannels * sizeof(float);
275 float freqAdjust = dsb->freqAdjust;
276 float freqAcc_start = *freqAcc;
277 float freqAcc_end = freqAcc_start + count * freqAdjust;
278 UINT dsbfirstep = dsb->firstep;
279 UINT channels = dsb->mix_channels;
280 UINT max_ipos = freqAcc_start + count * freqAdjust;
282 UINT fir_cachesize = (fir_len + dsbfirstep - 2) / dsbfirstep;
283 UINT required_input = max_ipos + fir_cachesize;
285 float* intermediate = HeapAlloc(GetProcessHeap(), 0,
286 sizeof(float) * required_input * channels);
288 float* fir_copy = HeapAlloc(GetProcessHeap(), 0,
289 sizeof(float) * fir_cachesize);
291 /* Important: this buffer MUST be non-interleaved
292 * if you want -msse3 to have any effect.
293 * This is good for CPU cache effects, too.
295 float* itmp = intermediate;
296 for (channel = 0; channel < channels; channel++)
297 for (i = 0; i < required_input; i++)
298 *(itmp++) = get_current_sample(dsb,
299 dsb->sec_mixpos + i * istride, channel);
301 for(i = 0; i < count; ++i) {
302 float total_fir_steps = (freqAcc_start + i * freqAdjust) * dsbfirstep;
303 UINT int_fir_steps = total_fir_steps;
304 UINT ipos = int_fir_steps / dsbfirstep;
306 UINT idx = (ipos + 1) * dsbfirstep - int_fir_steps - 1;
307 float rem = int_fir_steps + 1.0 - total_fir_steps;
309 int fir_used = 0;
310 while (idx < fir_len - 1) {
311 fir_copy[fir_used++] = fir[idx] * (1.0 - rem) + fir[idx + 1] * rem;
312 idx += dsb->firstep;
315 assert(fir_used <= fir_cachesize);
316 assert(ipos + fir_used <= required_input);
318 for (channel = 0; channel < dsb->mix_channels; channel++) {
319 int j;
320 float sum = 0.0;
321 float* cache = &intermediate[channel * required_input + ipos];
322 for (j = 0; j < fir_used; j++)
323 sum += fir_copy[j] * cache[j];
324 dsb->put(dsb, i * ostride, channel, sum * dsb->firgain);
328 freqAcc_end -= (int)freqAcc_end;
329 *freqAcc = freqAcc_end;
331 HeapFree(GetProcessHeap(), 0, fir_copy);
332 HeapFree(GetProcessHeap(), 0, intermediate);
334 return max_ipos;
337 static void cp_fields(IDirectSoundBufferImpl *dsb, UINT count, float *freqAcc)
339 DWORD ipos, adv;
341 if (dsb->freqAdjust == 1.0)
342 adv = cp_fields_noresample(dsb, count); /* *freqAcc is unmodified */
343 else
344 adv = cp_fields_resample(dsb, count, freqAcc);
346 ipos = dsb->sec_mixpos + adv * dsb->pwfx->nBlockAlign;
347 if (ipos >= dsb->buflen) {
348 if (dsb->playflags & DSBPLAY_LOOPING)
349 ipos %= dsb->buflen;
350 else {
351 ipos = 0;
352 dsb->state = STATE_STOPPED;
356 dsb->sec_mixpos = ipos;
360 * Calculate the distance between two buffer offsets, taking wraparound
361 * into account.
363 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
365 /* If these asserts fail, the problem is not here, but in the underlying code */
366 assert(ptr1 < buflen);
367 assert(ptr2 < buflen);
368 if (ptr1 >= ptr2) {
369 return ptr1 - ptr2;
370 } else {
371 return buflen + ptr1 - ptr2;
375 * Mix at most the given amount of data into the allocated temporary buffer
376 * of the given secondary buffer, starting from the dsb's first currently
377 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
378 * and bits-per-sample so that it is ideal for the primary buffer.
379 * Doesn't perform any mixing - this is a straight copy/convert operation.
381 * dsb = the secondary buffer
382 * writepos = Starting position of changed buffer
383 * len = number of bytes to resample from writepos
385 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
387 static void DSOUND_MixToTemporary(IDirectSoundBufferImpl *dsb, DWORD frames)
389 UINT size_bytes = frames * sizeof(float) * dsb->device->pwfx->nChannels;
391 if (dsb->device->tmp_buffer_len < size_bytes || !dsb->device->tmp_buffer)
393 dsb->device->tmp_buffer_len = size_bytes;
394 if (dsb->device->tmp_buffer)
395 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, size_bytes);
396 else
397 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, size_bytes);
400 cp_fields(dsb, frames, &dsb->freqAcc);
403 static void DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT frames)
405 INT i;
406 float vLeft, vRight;
407 UINT channels = dsb->device->pwfx->nChannels, chan;
409 TRACE("(%p,%d)\n",dsb,frames);
410 TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalLeftAmpFactor,
411 dsb->volpan.dwTotalRightAmpFactor);
413 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
414 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
415 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
416 return; /* Nothing to do */
418 if (channels != 1 && channels != 2)
420 FIXME("There is no support for %u channels\n", channels);
421 return;
424 vLeft = dsb->volpan.dwTotalLeftAmpFactor / ((float)0xFFFF);
425 vRight = dsb->volpan.dwTotalRightAmpFactor / ((float)0xFFFF);
426 for(i = 0; i < frames; ++i){
427 for(chan = 0; chan < channels; ++chan){
428 if(chan == 0)
429 dsb->device->tmp_buffer[i * channels + chan] *= vLeft;
430 else
431 dsb->device->tmp_buffer[i * channels + chan] *= vRight;
437 * Mix (at most) the given number of bytes into the given position of the
438 * device buffer, from the secondary buffer "dsb" (starting at the current
439 * mix position for that buffer).
441 * Returns the number of bytes actually mixed into the device buffer. This
442 * will match fraglen unless the end of the secondary buffer is reached
443 * (and it is not looping).
445 * dsb = the secondary buffer to mix from
446 * writepos = position (offset) in device buffer to write at
447 * fraglen = number of bytes to mix
449 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
451 INT len = fraglen;
452 float *ibuf;
453 DWORD oldpos;
454 UINT frames = fraglen / dsb->device->pwfx->nBlockAlign;
456 TRACE("sec_mixpos=%d/%d\n", dsb->sec_mixpos, dsb->buflen);
457 TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
459 if (len % dsb->device->pwfx->nBlockAlign) {
460 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
461 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
462 len -= len % nBlockAlign; /* data alignment */
465 /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
466 oldpos = dsb->sec_mixpos;
468 DSOUND_MixToTemporary(dsb, frames);
469 ibuf = dsb->device->tmp_buffer;
471 /* Apply volume if needed */
472 DSOUND_MixerVol(dsb, frames);
474 mixieee32(ibuf, dsb->device->mix_buffer, frames * dsb->device->pwfx->nChannels);
476 /* check for notification positions */
477 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
478 dsb->state != STATE_STARTING) {
479 INT ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
480 DSOUND_CheckEvent(dsb, oldpos, ilen);
483 return len;
487 * Mix some frames from the given secondary buffer "dsb" into the device
488 * primary buffer.
490 * dsb = the secondary buffer
491 * playpos = the current play position in the device buffer (primary buffer)
492 * writepos = the current safe-to-write position in the device buffer
493 * mixlen = the maximum number of bytes in the primary buffer to mix, from the
494 * current writepos.
496 * Returns: the number of bytes beyond the writepos that were mixed.
498 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD mixlen)
500 DWORD primary_done = 0;
502 TRACE("(%p,%d,%d)\n",dsb,writepos,mixlen);
503 TRACE("writepos=%d, mixlen=%d\n", writepos, mixlen);
504 TRACE("looping=%d, leadin=%d\n", dsb->playflags, dsb->leadin);
506 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
507 /* FIXME: Is this needed? */
508 if (dsb->leadin && dsb->state == STATE_STARTING) {
509 if (mixlen > 2 * dsb->device->fraglen) {
510 primary_done = mixlen - 2 * dsb->device->fraglen;
511 mixlen = 2 * dsb->device->fraglen;
512 writepos += primary_done;
513 dsb->sec_mixpos += (primary_done / dsb->device->pwfx->nBlockAlign) *
514 dsb->pwfx->nBlockAlign * dsb->freqAdjust;
518 dsb->leadin = FALSE;
520 TRACE("mixlen (primary) = %i\n", mixlen);
522 /* First try to mix to the end of the buffer if possible
523 * Theoretically it would allow for better optimization
525 primary_done += DSOUND_MixInBuffer(dsb, writepos, mixlen);
527 TRACE("total mixed data=%d\n", primary_done);
529 /* Report back the total prebuffered amount for this buffer */
530 return primary_done;
534 * For a DirectSoundDevice, go through all the currently playing buffers and
535 * mix them in to the device buffer.
537 * writepos = the current safe-to-write position in the primary buffer
538 * mixlen = the maximum amount to mix into the primary buffer
539 * (beyond the current writepos)
540 * recover = true if the sound device may have been reset and the write
541 * position in the device buffer changed
542 * all_stopped = reports back if all buffers have stopped
544 * Returns: the length beyond the writepos that was mixed to.
547 static void DSOUND_MixToPrimary(const DirectSoundDevice *device, DWORD writepos, DWORD mixlen, BOOL recover, BOOL *all_stopped)
549 INT i;
550 IDirectSoundBufferImpl *dsb;
552 /* unless we find a running buffer, all have stopped */
553 *all_stopped = TRUE;
555 TRACE("(%d,%d,%d)\n", writepos, mixlen, recover);
556 for (i = 0; i < device->nrofbuffers; i++) {
557 dsb = device->buffers[i];
559 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
561 if (dsb->buflen && dsb->state) {
562 TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
563 RtlAcquireResourceShared(&dsb->lock, TRUE);
564 /* if buffer is stopping it is stopped now */
565 if (dsb->state == STATE_STOPPING) {
566 dsb->state = STATE_STOPPED;
567 DSOUND_CheckEvent(dsb, 0, 0);
568 } else if (dsb->state != STATE_STOPPED) {
570 /* if the buffer was starting, it must be playing now */
571 if (dsb->state == STATE_STARTING)
572 dsb->state = STATE_PLAYING;
574 /* mix next buffer into the main buffer */
575 DSOUND_MixOne(dsb, writepos, mixlen);
577 *all_stopped = FALSE;
579 RtlReleaseResource(&dsb->lock);
585 * Add buffers to the emulated wave device system.
587 * device = The current dsound playback device
588 * force = If TRUE, the function will buffer up as many frags as possible,
589 * even though and will ignore the actual state of the primary buffer.
591 * Returns: None
594 static void DSOUND_WaveQueue(DirectSoundDevice *device, BOOL force)
596 DWORD prebuf_frames, prebuf_bytes, read_offs_bytes;
597 BYTE *buffer;
598 HRESULT hr;
600 TRACE("(%p)\n", device);
602 read_offs_bytes = (device->playing_offs_bytes + device->in_mmdev_bytes) % device->buflen;
604 TRACE("read_offs_bytes = %u, playing_offs_bytes = %u, in_mmdev_bytes: %u, prebuf = %u\n",
605 read_offs_bytes, device->playing_offs_bytes, device->in_mmdev_bytes, device->prebuf);
607 if (!force)
609 if(device->mixpos < device->playing_offs_bytes)
610 prebuf_bytes = device->mixpos + device->buflen - device->playing_offs_bytes;
611 else
612 prebuf_bytes = device->mixpos - device->playing_offs_bytes;
614 else
615 /* buffer the maximum amount of frags */
616 prebuf_bytes = device->prebuf * device->fraglen;
618 /* limit to the queue we have left */
619 if(device->in_mmdev_bytes + prebuf_bytes > device->prebuf * device->fraglen)
620 prebuf_bytes = device->prebuf * device->fraglen - device->in_mmdev_bytes;
622 TRACE("prebuf_bytes = %u\n", prebuf_bytes);
624 if(!prebuf_bytes)
625 return;
627 if(prebuf_bytes + read_offs_bytes > device->buflen){
628 DWORD chunk_bytes = device->buflen - read_offs_bytes;
629 prebuf_frames = chunk_bytes / device->pwfx->nBlockAlign;
630 prebuf_bytes -= chunk_bytes;
631 }else{
632 prebuf_frames = prebuf_bytes / device->pwfx->nBlockAlign;
633 prebuf_bytes = 0;
636 hr = IAudioRenderClient_GetBuffer(device->render, prebuf_frames, &buffer);
637 if(FAILED(hr)){
638 WARN("GetBuffer failed: %08x\n", hr);
639 return;
642 memcpy(buffer, device->buffer + read_offs_bytes,
643 prebuf_frames * device->pwfx->nBlockAlign);
645 hr = IAudioRenderClient_ReleaseBuffer(device->render, prebuf_frames, 0);
646 if(FAILED(hr)){
647 WARN("ReleaseBuffer failed: %08x\n", hr);
648 return;
651 device->in_mmdev_bytes += prebuf_frames * device->pwfx->nBlockAlign;
653 /* check if anything wrapped */
654 if(prebuf_bytes > 0){
655 prebuf_frames = prebuf_bytes / device->pwfx->nBlockAlign;
657 hr = IAudioRenderClient_GetBuffer(device->render, prebuf_frames, &buffer);
658 if(FAILED(hr)){
659 WARN("GetBuffer failed: %08x\n", hr);
660 return;
663 memcpy(buffer, device->buffer, prebuf_frames * device->pwfx->nBlockAlign);
665 hr = IAudioRenderClient_ReleaseBuffer(device->render, prebuf_frames, 0);
666 if(FAILED(hr)){
667 WARN("ReleaseBuffer failed: %08x\n", hr);
668 return;
670 device->in_mmdev_bytes += prebuf_frames * device->pwfx->nBlockAlign;
673 TRACE("in_mmdev_bytes now = %i\n", device->in_mmdev_bytes);
677 * Perform mixing for a Direct Sound device. That is, go through all the
678 * secondary buffers (the sound bites currently playing) and mix them in
679 * to the primary buffer (the device buffer).
681 * The mixing procedure goes:
683 * secondary->buffer (secondary format)
684 * =[Resample]=> device->tmp_buffer (float format)
685 * =[Volume]=> device->tmp_buffer (float format)
686 * =[Mix]=> device->mix_buffer (float format)
687 * =[Reformat]=> device->buffer (device format)
689 static void DSOUND_PerformMix(DirectSoundDevice *device)
691 UINT32 pad, to_mix_frags, to_mix_bytes;
692 HRESULT hr;
694 TRACE("(%p)\n", device);
696 /* **** */
697 EnterCriticalSection(&device->mixlock);
699 hr = IAudioClient_GetCurrentPadding(device->client, &pad);
700 if(FAILED(hr)){
701 WARN("GetCurrentPadding failed: %08x\n", hr);
702 LeaveCriticalSection(&device->mixlock);
703 return;
706 to_mix_frags = device->prebuf - (pad * device->pwfx->nBlockAlign + device->fraglen - 1) / device->fraglen;
708 to_mix_bytes = to_mix_frags * device->fraglen;
710 if(device->in_mmdev_bytes > 0){
711 DWORD delta_bytes = min(to_mix_bytes, device->in_mmdev_bytes);
712 device->in_mmdev_bytes -= delta_bytes;
713 device->playing_offs_bytes += delta_bytes;
714 device->playing_offs_bytes %= device->buflen;
717 if (device->priolevel != DSSCL_WRITEPRIMARY) {
718 BOOL recover = FALSE, all_stopped = FALSE;
719 DWORD playpos, writepos, writelead, maxq, prebuff_max, prebuff_left, size1, size2;
720 LPVOID buf1, buf2;
721 int nfiller;
723 /* the sound of silence */
724 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
726 /* get the position in the primary buffer */
727 if (DSOUND_PrimaryGetPosition(device, &playpos, &writepos) != 0){
728 LeaveCriticalSection(&(device->mixlock));
729 return;
732 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
733 playpos,writepos,device->playpos,device->mixpos,device->buflen);
734 assert(device->playpos < device->buflen);
736 /* calc maximum prebuff */
737 prebuff_max = (device->prebuf * device->fraglen);
739 /* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
740 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
741 writelead = DSOUND_BufPtrDiff(device->buflen, writepos, playpos);
743 /* check for underrun. underrun occurs when the write position passes the mix position
744 * also wipe out just-played sound data */
745 if((prebuff_left > prebuff_max) || (device->state == STATE_STOPPED) || (device->state == STATE_STARTING)){
746 if (device->state == STATE_STOPPING || device->state == STATE_PLAYING)
747 WARN("Probable buffer underrun\n");
748 else TRACE("Buffer starting or buffer underrun\n");
750 /* recover mixing for all buffers */
751 recover = TRUE;
753 /* reset mix position to write position */
754 device->mixpos = writepos;
756 ZeroMemory(device->buffer, device->buflen);
757 } else if (playpos < device->playpos) {
758 buf1 = device->buffer + device->playpos;
759 buf2 = device->buffer;
760 size1 = device->buflen - device->playpos;
761 size2 = playpos;
762 FillMemory(buf1, size1, nfiller);
763 if (playpos && (!buf2 || !size2))
764 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__, device->playpos, device->mixpos, playpos, writepos);
765 FillMemory(buf2, size2, nfiller);
766 } else {
767 buf1 = device->buffer + device->playpos;
768 buf2 = NULL;
769 size1 = playpos - device->playpos;
770 size2 = 0;
771 FillMemory(buf1, size1, nfiller);
773 device->playpos = playpos;
775 /* find the maximum we can prebuffer from current write position */
776 maxq = (writelead < prebuff_max) ? (prebuff_max - writelead) : 0;
778 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
779 prebuff_left, device->prebuf, device->fraglen, prebuff_max, writelead);
781 ZeroMemory(device->mix_buffer, device->mix_buffer_len);
783 /* do the mixing */
784 DSOUND_MixToPrimary(device, writepos, maxq, recover, &all_stopped);
786 if (maxq + writepos > device->buflen)
788 DWORD todo = device->buflen - writepos;
789 DWORD offs_float = (todo / device->pwfx->nBlockAlign) * device->pwfx->nChannels;
790 device->normfunction(device->mix_buffer, device->buffer + writepos, todo);
791 device->normfunction(device->mix_buffer + offs_float, device->buffer, maxq - todo);
793 else
794 device->normfunction(device->mix_buffer, device->buffer + writepos, maxq);
796 /* update the mix position, taking wrap-around into account */
797 device->mixpos = writepos + maxq;
798 device->mixpos %= device->buflen;
800 /* update prebuff left */
801 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
803 /* check if have a whole fragment */
804 if (prebuff_left >= device->fraglen){
806 /* update the wave queue */
807 DSOUND_WaveQueue(device, FALSE);
809 /* buffers are full. start playing if applicable */
810 if(device->state == STATE_STARTING){
811 TRACE("started primary buffer\n");
812 if(DSOUND_PrimaryPlay(device) != DS_OK){
813 WARN("DSOUND_PrimaryPlay failed\n");
815 else{
816 /* we are playing now */
817 device->state = STATE_PLAYING;
821 /* buffers are full. start stopping if applicable */
822 if(device->state == STATE_STOPPED){
823 TRACE("restarting primary buffer\n");
824 if(DSOUND_PrimaryPlay(device) != DS_OK){
825 WARN("DSOUND_PrimaryPlay failed\n");
827 else{
828 /* start stopping again. as soon as there is no more data, it will stop */
829 device->state = STATE_STOPPING;
834 /* if device was stopping, its for sure stopped when all buffers have stopped */
835 else if((all_stopped == TRUE) && (device->state == STATE_STOPPING)){
836 TRACE("All buffers have stopped. Stopping primary buffer\n");
837 device->state = STATE_STOPPED;
839 /* stop the primary buffer now */
840 DSOUND_PrimaryStop(device);
843 } else if (device->state != STATE_STOPPED) {
845 DSOUND_WaveQueue(device, TRUE);
847 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
848 if (device->state == STATE_STARTING) {
849 if (DSOUND_PrimaryPlay(device) != DS_OK)
850 WARN("DSOUND_PrimaryPlay failed\n");
851 else
852 device->state = STATE_PLAYING;
854 else if (device->state == STATE_STOPPING) {
855 if (DSOUND_PrimaryStop(device) != DS_OK)
856 WARN("DSOUND_PrimaryStop failed\n");
857 else
858 device->state = STATE_STOPPED;
862 LeaveCriticalSection(&(device->mixlock));
863 /* **** */
866 DWORD CALLBACK DSOUND_mixthread(void *p)
868 DirectSoundDevice *dev = p;
869 TRACE("(%p)\n", dev);
871 while (dev->ref) {
872 DWORD ret;
875 * Some audio drivers are retarded and won't fire after being
876 * stopped, add a timeout to handle this.
878 ret = WaitForSingleObject(dev->sleepev, dev->sleeptime);
879 if (ret == WAIT_FAILED)
880 WARN("wait returned error %u %08x!\n", GetLastError(), GetLastError());
881 else if (ret != WAIT_OBJECT_0)
882 WARN("wait returned %08x!\n", ret);
883 if (!dev->ref)
884 break;
886 RtlAcquireResourceShared(&(dev->buffer_list_lock), TRUE);
887 DSOUND_PerformMix(dev);
888 RtlReleaseResource(&(dev->buffer_list_lock));
890 return 0;