dsound: Remove hardware acceleration support.
[wine/multimedia.git] / dlls / dsound / mixer.c
blobe574790798b169f2756718a665a10752a7fb5130
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 NONAMELESSSTRUCT
30 #define NONAMELESSUNION
31 #include "windef.h"
32 #include "winbase.h"
33 #include "mmsystem.h"
34 #include "wingdi.h"
35 #include "mmreg.h"
36 #include "winternl.h"
37 #include "wine/debug.h"
38 #include "dsound.h"
39 #include "ks.h"
40 #include "ksmedia.h"
41 #include "dsound_private.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 */
52 volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
53 /* FIXME: dwPan{Left|Right}AmpFactor */
55 /* FIXME: use calculated vol and pan ampfactors */
56 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
57 volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
58 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
59 volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
61 TRACE("left = %x, right = %x\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
64 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
66 double left,right;
67 TRACE("(%p)\n",volpan);
69 TRACE("left=%x, right=%x\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
70 if (volpan->dwTotalLeftAmpFactor==0)
71 left=-10000;
72 else
73 left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
74 if (volpan->dwTotalRightAmpFactor==0)
75 right=-10000;
76 else
77 right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
78 if (left<right)
80 volpan->lVolume=right;
81 volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
83 else
85 volpan->lVolume=left;
86 volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
88 if (volpan->lVolume < -10000)
89 volpan->lVolume=-10000;
90 volpan->lPan=right-left;
91 if (volpan->lPan < -10000)
92 volpan->lPan=-10000;
94 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
97 /** Convert a primary buffer position to a pointer position for device->mix_buffer
98 * device: DirectSoundDevice for which to calculate
99 * pos: Primary buffer position to converts
100 * Returns: Offset for mix_buffer
102 DWORD DSOUND_bufpos_to_mixpos(const DirectSoundDevice* device, DWORD pos)
104 DWORD ret = pos * 32 / device->pwfx->wBitsPerSample;
105 if (device->pwfx->wBitsPerSample == 32)
106 ret *= 2;
107 return ret;
110 /* NOTE: Not all secpos have to always be mapped to a bufpos, other way around is always the case
111 * DWORD64 is used here because a single DWORD wouldn't be big enough to fit the freqAcc for big buffers
113 /** This function converts a 'native' sample pointer to a resampled pointer that fits for primary
114 * secmixpos is used to decide which freqAcc is needed
115 * overshot tells what the 'actual' secpos is now (optional)
117 DWORD DSOUND_secpos_to_bufpos(const IDirectSoundBufferImpl *dsb, DWORD secpos, DWORD secmixpos, DWORD* overshot)
119 DWORD64 framelen = secpos / dsb->pwfx->nBlockAlign;
120 DWORD64 freqAdjust = dsb->freqAdjust;
121 DWORD64 acc, freqAcc;
123 if (secpos < secmixpos)
124 freqAcc = dsb->freqAccNext;
125 else freqAcc = dsb->freqAcc;
126 acc = (framelen << DSOUND_FREQSHIFT) + (freqAdjust - 1 - freqAcc);
127 acc /= freqAdjust;
128 if (overshot)
130 DWORD64 oshot = acc * freqAdjust + freqAcc;
131 assert(oshot >= framelen << DSOUND_FREQSHIFT);
132 oshot -= framelen << DSOUND_FREQSHIFT;
133 *overshot = (DWORD)oshot;
134 assert(*overshot < dsb->freqAdjust);
136 return (DWORD)acc * dsb->device->pwfx->nBlockAlign;
139 /** Convert a resampled pointer that fits for primary to a 'native' sample pointer
140 * freqAccNext is used here rather than freqAcc: In case the app wants to fill up to
141 * the play position it won't overwrite it
143 static DWORD DSOUND_bufpos_to_secpos(const IDirectSoundBufferImpl *dsb, DWORD bufpos)
145 DWORD oAdv = dsb->device->pwfx->nBlockAlign, iAdv = dsb->pwfx->nBlockAlign, pos;
146 DWORD64 framelen;
147 DWORD64 acc;
149 framelen = bufpos/oAdv;
150 acc = framelen * (DWORD64)dsb->freqAdjust + (DWORD64)dsb->freqAccNext;
151 acc = acc >> DSOUND_FREQSHIFT;
152 pos = (DWORD)acc * iAdv;
153 if (pos >= dsb->buflen)
154 /* Because of differences between freqAcc and freqAccNext, this might happen */
155 pos = dsb->buflen - iAdv;
156 TRACE("Converted %d/%d to %d/%d\n", bufpos, dsb->tmp_buffer_len, pos, dsb->buflen);
157 return pos;
161 * Move freqAccNext to freqAcc, and find new values for buffer length and freqAccNext
163 static void DSOUND_RecalcFreqAcc(IDirectSoundBufferImpl *dsb)
165 if (!dsb->freqneeded) return;
166 dsb->freqAcc = dsb->freqAccNext;
167 dsb->tmp_buffer_len = DSOUND_secpos_to_bufpos(dsb, dsb->buflen, 0, &dsb->freqAccNext);
168 TRACE("New freqadjust: %04x, new buflen: %d\n", dsb->freqAccNext, dsb->tmp_buffer_len);
172 * Recalculate the size for temporary buffer, and new writelead
173 * Should be called when one of the following things occur:
174 * - Primary buffer format is changed
175 * - This buffer format (frequency) is changed
177 * After this, DSOUND_MixToTemporary(dsb, 0, dsb->buflen) should
178 * be called to refill the temporary buffer with data.
180 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
182 BOOL needremix = TRUE, needresample = (dsb->freq != dsb->device->pwfx->nSamplesPerSec);
183 DWORD bAlign = dsb->pwfx->nBlockAlign, pAlign = dsb->device->pwfx->nBlockAlign;
184 WAVEFORMATEXTENSIBLE *pwfxe;
185 BOOL ieee = FALSE;
187 TRACE("(%p)\n",dsb);
189 pwfxe = (WAVEFORMATEXTENSIBLE *) dsb->pwfx;
191 if ((pwfxe->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) || ((pwfxe->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
192 && (IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))))
193 ieee = TRUE;
195 /* calculate the 10ms write lead */
196 dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
198 if ((dsb->pwfx->wBitsPerSample == dsb->device->pwfx->wBitsPerSample) &&
199 (dsb->pwfx->nChannels == dsb->device->pwfx->nChannels) && !needresample && !ieee)
200 needremix = FALSE;
201 HeapFree(GetProcessHeap(), 0, dsb->tmp_buffer);
202 dsb->tmp_buffer = NULL;
203 dsb->max_buffer_len = dsb->freqAcc = dsb->freqAccNext = 0;
204 dsb->freqneeded = needresample;
206 if (ieee)
207 dsb->convert = convertbpp[4][dsb->device->pwfx->wBitsPerSample/8 - 1];
208 else
209 dsb->convert = convertbpp[dsb->pwfx->wBitsPerSample/8 - 1][dsb->device->pwfx->wBitsPerSample/8 - 1];
211 dsb->resampleinmixer = FALSE;
213 if (needremix)
215 if (needresample)
216 DSOUND_RecalcFreqAcc(dsb);
217 else
218 dsb->tmp_buffer_len = dsb->buflen / bAlign * pAlign;
219 dsb->max_buffer_len = dsb->tmp_buffer_len;
220 if ((dsb->max_buffer_len <= dsb->device->buflen || dsb->max_buffer_len < ds_snd_shadow_maxsize * 1024 * 1024) && ds_snd_shadow_maxsize >= 0)
221 dsb->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, dsb->max_buffer_len);
222 if (dsb->tmp_buffer)
223 FillMemory(dsb->tmp_buffer, dsb->tmp_buffer_len, dsb->device->pwfx->wBitsPerSample == 8 ? 128 : 0);
224 else
225 dsb->resampleinmixer = TRUE;
227 else dsb->max_buffer_len = dsb->tmp_buffer_len = dsb->buflen;
228 dsb->buf_mixpos = DSOUND_secpos_to_bufpos(dsb, dsb->sec_mixpos, 0, NULL);
232 * Check for application callback requests for when the play position
233 * reaches certain points.
235 * The offsets that will be triggered will be those between the recorded
236 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
237 * beyond that position.
239 void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
241 int i;
242 DWORD offset;
243 LPDSBPOSITIONNOTIFY event;
244 TRACE("(%p,%d)\n",dsb,len);
246 if (dsb->nrofnotifies == 0)
247 return;
249 TRACE("(%p) buflen = %d, playpos = %d, len = %d\n",
250 dsb, dsb->buflen, playpos, len);
251 for (i = 0; i < dsb->nrofnotifies ; i++) {
252 event = dsb->notifies + i;
253 offset = event->dwOffset;
254 TRACE("checking %d, position %d, event = %p\n",
255 i, offset, event->hEventNotify);
256 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
257 /* OK. [Inside DirectX, p274] */
258 /* Windows does not seem to enforce this, and some apps rely */
259 /* on that, so we can't stop there. */
260 /* */
261 /* This also means we can't sort the entries by offset, */
262 /* because DSBPN_OFFSETSTOP == -1 */
263 if (offset == DSBPN_OFFSETSTOP) {
264 if (dsb->state == STATE_STOPPED) {
265 SetEvent(event->hEventNotify);
266 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
268 continue;
270 if ((playpos + len) >= dsb->buflen) {
271 if ((offset < ((playpos + len) % dsb->buflen)) ||
272 (offset >= playpos)) {
273 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
274 SetEvent(event->hEventNotify);
276 } else {
277 if ((offset >= playpos) && (offset < (playpos + len))) {
278 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
279 SetEvent(event->hEventNotify);
286 * Copy a single frame from the given input buffer to the given output buffer.
287 * Translate 8 <-> 16 bits and mono <-> stereo
289 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, const BYTE *ibuf, BYTE *obuf,
290 UINT istride, UINT ostride, UINT count, UINT freqAcc, UINT adj)
292 DirectSoundDevice *device = dsb->device;
293 INT istep = dsb->pwfx->wBitsPerSample / 8, ostep = device->pwfx->wBitsPerSample / 8;
295 if (device->pwfx->nChannels == dsb->pwfx->nChannels ||
296 (device->pwfx->nChannels == 2 && dsb->pwfx->nChannels == 6) ||
297 (device->pwfx->nChannels == 8 && dsb->pwfx->nChannels == 2) ||
298 (device->pwfx->nChannels == 6 && dsb->pwfx->nChannels == 2)) {
299 dsb->convert(ibuf, obuf, istride, ostride, count, freqAcc, adj);
300 if (device->pwfx->nChannels == 2 || dsb->pwfx->nChannels == 2)
301 dsb->convert(ibuf + istep, obuf + ostep, istride, ostride, count, freqAcc, adj);
302 return;
305 if (device->pwfx->nChannels == 1 && dsb->pwfx->nChannels == 2)
307 dsb->convert(ibuf, obuf, istride, ostride, count, freqAcc, adj);
308 return;
311 if (device->pwfx->nChannels == 2 && dsb->pwfx->nChannels == 1)
313 dsb->convert(ibuf, obuf, istride, ostride, count, freqAcc, adj);
314 dsb->convert(ibuf, obuf + ostep, istride, ostride, count, freqAcc, adj);
315 return;
318 WARN("Unable to remap channels: device=%u, buffer=%u\n", device->pwfx->nChannels,
319 dsb->pwfx->nChannels);
323 * Calculate the distance between two buffer offsets, taking wraparound
324 * into account.
326 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
328 /* If these asserts fail, the problem is not here, but in the underlying code */
329 assert(ptr1 < buflen);
330 assert(ptr2 < buflen);
331 if (ptr1 >= ptr2) {
332 return ptr1 - ptr2;
333 } else {
334 return buflen + ptr1 - ptr2;
338 * Mix at most the given amount of data into the allocated temporary buffer
339 * of the given secondary buffer, starting from the dsb's first currently
340 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
341 * and bits-per-sample so that it is ideal for the primary buffer.
342 * Doesn't perform any mixing - this is a straight copy/convert operation.
344 * dsb = the secondary buffer
345 * writepos = Starting position of changed buffer
346 * len = number of bytes to resample from writepos
348 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
350 void DSOUND_MixToTemporary(const IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len, BOOL inmixer)
352 INT size;
353 BYTE *ibp, *obp, *obp_begin;
354 INT iAdvance = dsb->pwfx->nBlockAlign;
355 INT oAdvance = dsb->device->pwfx->nBlockAlign;
356 DWORD freqAcc, target_writepos = 0, overshot, maxlen;
358 /* We resample only when needed */
359 if ((dsb->tmp_buffer && inmixer) || (!dsb->tmp_buffer && !inmixer) || dsb->resampleinmixer != inmixer)
360 return;
362 assert(writepos + len <= dsb->buflen);
363 if (inmixer && writepos + len < dsb->buflen)
364 len += dsb->pwfx->nBlockAlign;
366 maxlen = DSOUND_secpos_to_bufpos(dsb, len, 0, NULL);
368 ibp = dsb->buffer->memory + writepos;
369 if (!inmixer)
370 obp_begin = dsb->tmp_buffer;
371 else if (dsb->device->tmp_buffer_len < maxlen || !dsb->device->tmp_buffer)
373 dsb->device->tmp_buffer_len = maxlen;
374 if (dsb->device->tmp_buffer)
375 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, maxlen);
376 else
377 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, maxlen);
378 obp_begin = dsb->device->tmp_buffer;
380 else
381 obp_begin = dsb->device->tmp_buffer;
383 TRACE("(%p, %p)\n", dsb, ibp);
384 size = len / iAdvance;
386 /* Check for same sample rate */
387 if (dsb->freq == dsb->device->pwfx->nSamplesPerSec) {
388 TRACE("(%p) Same sample rate %d = primary %d\n", dsb,
389 dsb->freq, dsb->device->pwfx->nSamplesPerSec);
390 obp = obp_begin;
391 if (!inmixer)
392 obp += writepos/iAdvance*oAdvance;
394 cp_fields(dsb, ibp, obp, iAdvance, oAdvance, size, 0, 1 << DSOUND_FREQSHIFT);
395 return;
398 /* Mix in different sample rates */
399 TRACE("(%p) Adjusting frequency: %d -> %d\n", dsb, dsb->freq, dsb->device->pwfx->nSamplesPerSec);
401 target_writepos = DSOUND_secpos_to_bufpos(dsb, writepos, dsb->sec_mixpos, &freqAcc);
402 overshot = freqAcc >> DSOUND_FREQSHIFT;
403 if (overshot)
405 if (overshot >= size)
406 return;
407 size -= overshot;
408 writepos += overshot * iAdvance;
409 if (writepos >= dsb->buflen)
410 return;
411 ibp = dsb->buffer->memory + writepos;
412 freqAcc &= (1 << DSOUND_FREQSHIFT) - 1;
413 TRACE("Overshot: %d, freqAcc: %04x\n", overshot, freqAcc);
416 if (!inmixer)
417 obp = obp_begin + target_writepos;
418 else obp = obp_begin;
420 /* FIXME: Small problem here when we're overwriting buf_mixpos, it then STILL uses old freqAcc, not sure if it matters or not */
421 cp_fields(dsb, ibp, obp, iAdvance, oAdvance, size, freqAcc, dsb->freqAdjust);
424 /** Apply volume to the given soundbuffer from (primary) position writepos and length len
425 * Returns: NULL if no volume needs to be applied
426 * or else a memory handle that holds 'len' volume adjusted buffer */
427 static LPBYTE DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT len)
429 INT i;
430 BYTE *bpc;
431 INT16 *bps, *mems;
432 DWORD vLeft, vRight;
433 INT nChannels = dsb->device->pwfx->nChannels;
434 LPBYTE mem = (dsb->tmp_buffer ? dsb->tmp_buffer : dsb->buffer->memory) + dsb->buf_mixpos;
436 if (dsb->resampleinmixer)
437 mem = dsb->device->tmp_buffer;
439 TRACE("(%p,%d)\n",dsb,len);
440 TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalLeftAmpFactor,
441 dsb->volpan.dwTotalRightAmpFactor);
443 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
444 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
445 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
446 return NULL; /* Nothing to do */
448 if (nChannels != 1 && nChannels != 2)
450 FIXME("There is no support for %d channels\n", nChannels);
451 return NULL;
454 if (dsb->device->pwfx->wBitsPerSample != 8 && dsb->device->pwfx->wBitsPerSample != 16)
456 FIXME("There is no support for %d bpp\n", dsb->device->pwfx->wBitsPerSample);
457 return NULL;
460 if (dsb->device->tmp_buffer_len < len || !dsb->device->tmp_buffer)
462 /* If we just resampled in DSOUND_MixToTemporary, we shouldn't need to resize here */
463 assert(!dsb->resampleinmixer);
464 dsb->device->tmp_buffer_len = len;
465 if (dsb->device->tmp_buffer)
466 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, len);
467 else
468 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
471 bpc = dsb->device->tmp_buffer;
472 bps = (INT16 *)bpc;
473 mems = (INT16 *)mem;
474 vLeft = dsb->volpan.dwTotalLeftAmpFactor;
475 if (nChannels > 1)
476 vRight = dsb->volpan.dwTotalRightAmpFactor;
477 else
478 vRight = vLeft;
480 switch (dsb->device->pwfx->wBitsPerSample) {
481 case 8:
482 /* 8-bit WAV is unsigned, but we need to operate */
483 /* on signed data for this to work properly */
484 for (i = 0; i < len-1; i+=2) {
485 *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
486 *(bpc++) = (((*(mem++) - 128) * vRight) >> 16) + 128;
488 if (len % 2 == 1 && nChannels == 1)
489 *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
490 break;
491 case 16:
492 /* 16-bit WAV is signed -- much better */
493 for (i = 0; i < len-3; i += 4) {
494 *(bps++) = (*(mems++) * vLeft) >> 16;
495 *(bps++) = (*(mems++) * vRight) >> 16;
497 if (len % 4 == 2 && nChannels == 1)
498 *(bps++) = ((INT)*(mems++) * vLeft) >> 16;
499 break;
501 return dsb->device->tmp_buffer;
505 * Mix (at most) the given number of bytes into the given position of the
506 * device buffer, from the secondary buffer "dsb" (starting at the current
507 * mix position for that buffer).
509 * Returns the number of bytes actually mixed into the device buffer. This
510 * will match fraglen unless the end of the secondary buffer is reached
511 * (and it is not looping).
513 * dsb = the secondary buffer to mix from
514 * writepos = position (offset) in device buffer to write at
515 * fraglen = number of bytes to mix
517 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
519 INT len = fraglen, ilen;
520 BYTE *ibuf = (dsb->tmp_buffer ? dsb->tmp_buffer : dsb->buffer->memory) + dsb->buf_mixpos, *volbuf;
521 DWORD oldpos, mixbufpos;
523 TRACE("buf_mixpos=%d/%d sec_mixpos=%d/%d\n", dsb->buf_mixpos, dsb->tmp_buffer_len, dsb->sec_mixpos, dsb->buflen);
524 TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
526 assert(dsb->buf_mixpos + len <= dsb->tmp_buffer_len);
528 if (len % dsb->device->pwfx->nBlockAlign) {
529 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
530 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
531 len -= len % nBlockAlign; /* data alignment */
534 /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
535 DSOUND_MixToTemporary(dsb, dsb->sec_mixpos, DSOUND_bufpos_to_secpos(dsb, dsb->buf_mixpos+len) - dsb->sec_mixpos, TRUE);
536 if (dsb->resampleinmixer)
537 ibuf = dsb->device->tmp_buffer;
539 /* Apply volume if needed */
540 volbuf = DSOUND_MixerVol(dsb, len);
541 if (volbuf)
542 ibuf = volbuf;
544 mixbufpos = DSOUND_bufpos_to_mixpos(dsb->device, writepos);
545 /* Now mix the temporary buffer into the devices main buffer */
546 if ((writepos + len) <= dsb->device->buflen)
547 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, len);
548 else
550 DWORD todo = dsb->device->buflen - writepos;
551 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, todo);
552 dsb->device->mixfunction(ibuf + todo, dsb->device->mix_buffer, len - todo);
555 oldpos = dsb->sec_mixpos;
556 dsb->buf_mixpos += len;
558 if (dsb->buf_mixpos >= dsb->tmp_buffer_len) {
559 if (dsb->buf_mixpos > dsb->tmp_buffer_len)
560 ERR("Mixpos (%u) past buflen (%u), capping...\n", dsb->buf_mixpos, dsb->tmp_buffer_len);
561 if (dsb->playflags & DSBPLAY_LOOPING) {
562 dsb->buf_mixpos -= dsb->tmp_buffer_len;
563 } else if (dsb->buf_mixpos >= dsb->tmp_buffer_len) {
564 dsb->buf_mixpos = dsb->sec_mixpos = 0;
565 dsb->state = STATE_STOPPED;
567 DSOUND_RecalcFreqAcc(dsb);
570 dsb->sec_mixpos = DSOUND_bufpos_to_secpos(dsb, dsb->buf_mixpos);
571 ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
572 /* check for notification positions */
573 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
574 dsb->state != STATE_STARTING) {
575 DSOUND_CheckEvent(dsb, oldpos, ilen);
578 /* increase mix position */
579 dsb->primary_mixpos += len;
580 if (dsb->primary_mixpos >= dsb->device->buflen)
581 dsb->primary_mixpos -= dsb->device->buflen;
582 return len;
586 * Mix some frames from the given secondary buffer "dsb" into the device
587 * primary buffer.
589 * dsb = the secondary buffer
590 * playpos = the current play position in the device buffer (primary buffer)
591 * writepos = the current safe-to-write position in the device buffer
592 * mixlen = the maximum number of bytes in the primary buffer to mix, from the
593 * current writepos.
595 * Returns: the number of bytes beyond the writepos that were mixed.
597 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD mixlen)
599 /* The buffer's primary_mixpos may be before or after the device
600 * buffer's mixpos, but both must be ahead of writepos. */
601 DWORD primary_done;
603 TRACE("(%p,%d,%d)\n",dsb,writepos,mixlen);
604 TRACE("writepos=%d, buf_mixpos=%d, primary_mixpos=%d, mixlen=%d\n", writepos, dsb->buf_mixpos, dsb->primary_mixpos, mixlen);
605 TRACE("looping=%d, leadin=%d, buflen=%d\n", dsb->playflags, dsb->leadin, dsb->tmp_buffer_len);
607 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
608 if (dsb->leadin && dsb->state == STATE_STARTING)
610 if (mixlen > 2 * dsb->device->fraglen)
612 dsb->primary_mixpos += mixlen - 2 * dsb->device->fraglen;
613 dsb->primary_mixpos %= dsb->device->buflen;
616 dsb->leadin = FALSE;
618 /* calculate how much pre-buffering has already been done for this buffer */
619 primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
621 /* sanity */
622 if(mixlen < primary_done)
624 /* Should *NEVER* happen */
625 ERR("Fatal error. Under/Overflow? primary_done=%d, mixpos=%d/%d (%d/%d), primary_mixpos=%d, writepos=%d, mixlen=%d\n", primary_done,dsb->buf_mixpos,dsb->tmp_buffer_len,dsb->sec_mixpos, dsb->buflen, dsb->primary_mixpos, writepos, mixlen);
626 dsb->primary_mixpos = writepos + mixlen;
627 dsb->primary_mixpos %= dsb->device->buflen;
628 return mixlen;
631 /* take into account already mixed data */
632 mixlen -= primary_done;
634 TRACE("primary_done=%d, mixlen (primary) = %i\n", primary_done, mixlen);
636 if (!mixlen)
637 return primary_done;
639 /* First try to mix to the end of the buffer if possible
640 * Theoretically it would allow for better optimization
642 if (mixlen + dsb->buf_mixpos >= dsb->tmp_buffer_len)
644 DWORD newmixed, mixfirst = dsb->tmp_buffer_len - dsb->buf_mixpos;
645 newmixed = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixfirst);
646 mixlen -= newmixed;
648 if (dsb->playflags & DSBPLAY_LOOPING)
649 while (newmixed && mixlen)
651 mixfirst = (dsb->tmp_buffer_len < mixlen ? dsb->tmp_buffer_len : mixlen);
652 newmixed = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixfirst);
653 mixlen -= newmixed;
656 else DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixlen);
658 /* re-calculate the primary done */
659 primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
661 TRACE("new primary_mixpos=%d, total mixed data=%d\n", dsb->primary_mixpos, primary_done);
663 /* Report back the total prebuffered amount for this buffer */
664 return primary_done;
668 * For a DirectSoundDevice, go through all the currently playing buffers and
669 * mix them in to the device buffer.
671 * writepos = the current safe-to-write position in the primary buffer
672 * mixlen = the maximum amount to mix into the primary buffer
673 * (beyond the current writepos)
674 * recover = true if the sound device may have been reset and the write
675 * position in the device buffer changed
676 * all_stopped = reports back if all buffers have stopped
678 * Returns: the length beyond the writepos that was mixed to.
681 static DWORD DSOUND_MixToPrimary(const DirectSoundDevice *device, DWORD writepos, DWORD mixlen, BOOL recover, BOOL *all_stopped)
683 INT i, len;
684 DWORD minlen = 0;
685 IDirectSoundBufferImpl *dsb;
687 /* unless we find a running buffer, all have stopped */
688 *all_stopped = TRUE;
690 TRACE("(%d,%d,%d)\n", writepos, mixlen, recover);
691 for (i = 0; i < device->nrofbuffers; i++) {
692 dsb = device->buffers[i];
694 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
696 if (dsb->buflen && dsb->state) {
697 TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
698 RtlAcquireResourceShared(&dsb->lock, TRUE);
699 /* if buffer is stopping it is stopped now */
700 if (dsb->state == STATE_STOPPING) {
701 dsb->state = STATE_STOPPED;
702 DSOUND_CheckEvent(dsb, 0, 0);
703 } else if (dsb->state != STATE_STOPPED) {
705 /* if recovering, reset the mix position */
706 if ((dsb->state == STATE_STARTING) || recover) {
707 dsb->primary_mixpos = writepos;
710 /* if the buffer was starting, it must be playing now */
711 if (dsb->state == STATE_STARTING)
712 dsb->state = STATE_PLAYING;
714 /* mix next buffer into the main buffer */
715 len = DSOUND_MixOne(dsb, writepos, mixlen);
717 if (!minlen) minlen = len;
719 /* record the minimum length mixed from all buffers */
720 /* we only want to return the length which *all* buffers have mixed */
721 else if (len) minlen = (len < minlen) ? len : minlen;
723 *all_stopped = FALSE;
725 RtlReleaseResource(&dsb->lock);
729 TRACE("Mixed at least %d from all buffers\n", minlen);
730 return minlen;
734 * Add buffers to the emulated wave device system.
736 * device = The current dsound playback device
737 * force = If TRUE, the function will buffer up as many frags as possible,
738 * even though and will ignore the actual state of the primary buffer.
740 * Returns: None
743 static void DSOUND_WaveQueue(DirectSoundDevice *device, BOOL force)
745 DWORD prebuf_frags, wave_writepos, wave_fragpos, i;
746 TRACE("(%p)\n", device);
748 /* calculate the current wave frag position */
749 wave_fragpos = (device->pwplay + device->pwqueue) % device->helfrags;
751 /* calculate the current wave write position */
752 wave_writepos = wave_fragpos * device->fraglen;
754 TRACE("wave_fragpos = %i, wave_writepos = %i, pwqueue = %i, prebuf = %i\n",
755 wave_fragpos, wave_writepos, device->pwqueue, device->prebuf);
757 if (!force)
759 /* check remaining prebuffered frags */
760 prebuf_frags = device->mixpos / device->fraglen;
761 if (prebuf_frags == device->helfrags)
762 --prebuf_frags;
763 TRACE("wave_fragpos = %d, mixpos_frags = %d\n", wave_fragpos, prebuf_frags);
764 if (prebuf_frags < wave_fragpos)
765 prebuf_frags += device->helfrags;
766 prebuf_frags -= wave_fragpos;
767 TRACE("wanted prebuf_frags = %d\n", prebuf_frags);
769 else
770 /* buffer the maximum amount of frags */
771 prebuf_frags = device->prebuf;
773 /* limit to the queue we have left */
774 if ((prebuf_frags + device->pwqueue) > device->prebuf)
775 prebuf_frags = device->prebuf - device->pwqueue;
777 TRACE("prebuf_frags = %i\n", prebuf_frags);
779 /* adjust queue */
780 device->pwqueue += prebuf_frags;
782 /* get out of CS when calling the wave system */
783 LeaveCriticalSection(&(device->mixlock));
784 /* **** */
786 /* queue up the new buffers */
787 for(i=0; i<prebuf_frags; i++){
788 TRACE("queueing wave buffer %i\n", wave_fragpos);
789 waveOutWrite(device->hwo, &device->pwave[wave_fragpos], sizeof(WAVEHDR));
790 wave_fragpos++;
791 wave_fragpos %= device->helfrags;
794 /* **** */
795 EnterCriticalSection(&(device->mixlock));
797 TRACE("queue now = %i\n", device->pwqueue);
801 * Perform mixing for a Direct Sound device. That is, go through all the
802 * secondary buffers (the sound bites currently playing) and mix them in
803 * to the primary buffer (the device buffer).
805 static void DSOUND_PerformMix(DirectSoundDevice *device)
807 TRACE("(%p)\n", device);
809 /* **** */
810 EnterCriticalSection(&(device->mixlock));
812 if (device->priolevel != DSSCL_WRITEPRIMARY) {
813 BOOL recover = FALSE, all_stopped = FALSE;
814 DWORD playpos, writepos, writelead, maxq, frag, prebuff_max, prebuff_left, size1, size2, mixplaypos, mixplaypos2;
815 LPVOID buf1, buf2;
816 int nfiller;
818 /* the sound of silence */
819 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
821 /* get the position in the primary buffer */
822 if (DSOUND_PrimaryGetPosition(device, &playpos, &writepos) != 0){
823 LeaveCriticalSection(&(device->mixlock));
824 return;
827 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
828 playpos,writepos,device->playpos,device->mixpos,device->buflen);
829 assert(device->playpos < device->buflen);
831 mixplaypos = DSOUND_bufpos_to_mixpos(device, device->playpos);
832 mixplaypos2 = DSOUND_bufpos_to_mixpos(device, playpos);
834 /* calc maximum prebuff */
835 prebuff_max = (device->prebuf * device->fraglen);
836 if (playpos + prebuff_max >= device->helfrags * device->fraglen)
837 prebuff_max += device->buflen - device->helfrags * device->fraglen;
839 /* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
840 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
841 writelead = DSOUND_BufPtrDiff(device->buflen, writepos, playpos);
843 /* check for underrun. underrun occurs when the write position passes the mix position
844 * also wipe out just-played sound data */
845 if((prebuff_left > prebuff_max) || (device->state == STATE_STOPPED) || (device->state == STATE_STARTING)){
846 if (device->state == STATE_STOPPING || device->state == STATE_PLAYING)
847 WARN("Probable buffer underrun\n");
848 else TRACE("Buffer starting or buffer underrun\n");
850 /* recover mixing for all buffers */
851 recover = TRUE;
853 /* reset mix position to write position */
854 device->mixpos = writepos;
856 ZeroMemory(device->mix_buffer, device->mix_buffer_len);
857 ZeroMemory(device->buffer, device->buflen);
858 } else if (playpos < device->playpos) {
859 buf1 = device->buffer + device->playpos;
860 buf2 = device->buffer;
861 size1 = device->buflen - device->playpos;
862 size2 = playpos;
863 FillMemory(device->mix_buffer + mixplaypos, device->mix_buffer_len - mixplaypos, 0);
864 FillMemory(device->mix_buffer, mixplaypos2, 0);
865 FillMemory(buf1, size1, nfiller);
866 if (playpos && (!buf2 || !size2))
867 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__, device->playpos, device->mixpos, playpos, writepos);
868 FillMemory(buf2, size2, nfiller);
869 } else {
870 buf1 = device->buffer + device->playpos;
871 buf2 = NULL;
872 size1 = playpos - device->playpos;
873 size2 = 0;
874 FillMemory(device->mix_buffer + mixplaypos, mixplaypos2 - mixplaypos, 0);
875 FillMemory(buf1, size1, nfiller);
876 if (buf2 && size2)
878 FIXME("%d: There should be no additional buffer here!!\n", __LINE__);
879 FillMemory(buf2, size2, nfiller);
882 device->playpos = playpos;
884 /* find the maximum we can prebuffer from current write position */
885 maxq = (writelead < prebuff_max) ? (prebuff_max - writelead) : 0;
887 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
888 prebuff_left, device->prebuf, device->fraglen, prebuff_max, writelead);
890 /* do the mixing */
891 frag = DSOUND_MixToPrimary(device, writepos, maxq, recover, &all_stopped);
893 if (frag + writepos > device->buflen)
895 DWORD todo = device->buflen - writepos;
896 device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, todo);
897 device->normfunction(device->mix_buffer, device->buffer, frag - todo);
899 else
900 device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, frag);
902 /* update the mix position, taking wrap-around into account */
903 device->mixpos = writepos + frag;
904 device->mixpos %= device->buflen;
906 /* update prebuff left */
907 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
909 /* check if have a whole fragment */
910 if (prebuff_left >= device->fraglen){
912 /* update the wave queue */
913 DSOUND_WaveQueue(device, FALSE);
915 /* buffers are full. start playing if applicable */
916 if(device->state == STATE_STARTING){
917 TRACE("started primary buffer\n");
918 if(DSOUND_PrimaryPlay(device) != DS_OK){
919 WARN("DSOUND_PrimaryPlay failed\n");
921 else{
922 /* we are playing now */
923 device->state = STATE_PLAYING;
927 /* buffers are full. start stopping if applicable */
928 if(device->state == STATE_STOPPED){
929 TRACE("restarting primary buffer\n");
930 if(DSOUND_PrimaryPlay(device) != DS_OK){
931 WARN("DSOUND_PrimaryPlay failed\n");
933 else{
934 /* start stopping again. as soon as there is no more data, it will stop */
935 device->state = STATE_STOPPING;
940 /* if device was stopping, its for sure stopped when all buffers have stopped */
941 else if((all_stopped == TRUE) && (device->state == STATE_STOPPING)){
942 TRACE("All buffers have stopped. Stopping primary buffer\n");
943 device->state = STATE_STOPPED;
945 /* stop the primary buffer now */
946 DSOUND_PrimaryStop(device);
949 } else {
951 DSOUND_WaveQueue(device, TRUE);
953 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
954 if (device->state == STATE_STARTING) {
955 if (DSOUND_PrimaryPlay(device) != DS_OK)
956 WARN("DSOUND_PrimaryPlay failed\n");
957 else
958 device->state = STATE_PLAYING;
960 else if (device->state == STATE_STOPPING) {
961 if (DSOUND_PrimaryStop(device) != DS_OK)
962 WARN("DSOUND_PrimaryStop failed\n");
963 else
964 device->state = STATE_STOPPED;
968 LeaveCriticalSection(&(device->mixlock));
969 /* **** */
972 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD_PTR dwUser,
973 DWORD_PTR dw1, DWORD_PTR dw2)
975 DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
976 DWORD start_time = GetTickCount();
977 DWORD end_time;
978 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
979 TRACE("entering at %d\n", start_time);
981 if (DSOUND_renderer[device->drvdesc.dnDevNode] != device) {
982 ERR("dsound died without killing us?\n");
983 timeKillEvent(timerID);
984 timeEndPeriod(DS_TIME_RES);
985 return;
988 RtlAcquireResourceShared(&(device->buffer_list_lock), TRUE);
990 if (device->ref)
991 DSOUND_PerformMix(device);
993 RtlReleaseResource(&(device->buffer_list_lock));
995 end_time = GetTickCount();
996 TRACE("completed processing at %d, duration = %d\n", end_time, end_time - start_time);
999 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1001 DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
1002 TRACE("(%p,%x,%lx,%lx,%lx)\n",hwo,msg,dwUser,dw1,dw2);
1003 TRACE("entering at %d, msg=%08x(%s)\n", GetTickCount(), msg,
1004 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
1005 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1007 /* check if packet completed from wave driver */
1008 if (msg == MM_WOM_DONE) {
1010 /* **** */
1011 EnterCriticalSection(&(device->mixlock));
1013 TRACE("done playing primary pos=%d\n", device->pwplay * device->fraglen);
1015 /* update playpos */
1016 device->pwplay++;
1017 device->pwplay %= device->helfrags;
1019 /* sanity */
1020 if(device->pwqueue == 0){
1021 ERR("Wave queue corrupted!\n");
1024 /* update queue */
1025 device->pwqueue--;
1027 LeaveCriticalSection(&(device->mixlock));
1028 /* **** */
1030 TRACE("completed\n");