dmscript: Merge the IClassFactory implementations.
[wine/testsucceed.git] / dlls / dsound / mixer.c
blob5ed8d909c9ad1d403916c4f8a0d3d7f1c1b26bc4
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 "dsdriver.h"
42 #include "dsound_private.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
46 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
48 double temp;
49 TRACE("(%p)\n",volpan);
51 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
52 /* the AmpFactors are expressed in 16.16 fixed point */
53 volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
54 /* FIXME: dwPan{Left|Right}AmpFactor */
56 /* FIXME: use calculated vol and pan ampfactors */
57 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
58 volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
59 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
60 volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
62 TRACE("left = %x, right = %x\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
65 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
67 double left,right;
68 TRACE("(%p)\n",volpan);
70 TRACE("left=%x, right=%x\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
71 if (volpan->dwTotalLeftAmpFactor==0)
72 left=-10000;
73 else
74 left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
75 if (volpan->dwTotalRightAmpFactor==0)
76 right=-10000;
77 else
78 right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
79 if (left<right)
81 volpan->lVolume=right;
82 volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
84 else
86 volpan->lVolume=left;
87 volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
89 if (volpan->lVolume < -10000)
90 volpan->lVolume=-10000;
91 volpan->lPan=right-left;
92 if (volpan->lPan < -10000)
93 volpan->lPan=-10000;
95 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
98 /** Convert a primary buffer position to a pointer position for device->mix_buffer
99 * device: DirectSoundDevice for which to calculate
100 * pos: Primary buffer position to converts
101 * Returns: Offset for mix_buffer
103 DWORD DSOUND_bufpos_to_mixpos(const DirectSoundDevice* device, DWORD pos)
105 DWORD ret = pos * 32 / device->pwfx->wBitsPerSample;
106 if (device->pwfx->wBitsPerSample == 32)
107 ret *= 2;
108 return ret;
111 /* NOTE: Not all secpos have to always be mapped to a bufpos, other way around is always the case
112 * DWORD64 is used here because a single DWORD wouldn't be big enough to fit the freqAcc for big buffers
114 /** This function converts a 'native' sample pointer to a resampled pointer that fits for primary
115 * secmixpos is used to decide which freqAcc is needed
116 * overshot tells what the 'actual' secpos is now (optional)
118 DWORD DSOUND_secpos_to_bufpos(const IDirectSoundBufferImpl *dsb, DWORD secpos, DWORD secmixpos, DWORD* overshot)
120 DWORD64 framelen = secpos / dsb->pwfx->nBlockAlign;
121 DWORD64 freqAdjust = dsb->freqAdjust;
122 DWORD64 acc, freqAcc;
124 if (secpos < secmixpos)
125 freqAcc = dsb->freqAccNext;
126 else freqAcc = dsb->freqAcc;
127 acc = (framelen << DSOUND_FREQSHIFT) + (freqAdjust - 1 - freqAcc);
128 acc /= freqAdjust;
129 if (overshot)
131 DWORD64 oshot = acc * freqAdjust + freqAcc;
132 assert(oshot >= framelen << DSOUND_FREQSHIFT);
133 oshot -= framelen << DSOUND_FREQSHIFT;
134 *overshot = (DWORD)oshot;
135 assert(*overshot < dsb->freqAdjust);
137 return (DWORD)acc * dsb->device->pwfx->nBlockAlign;
140 /** Convert a resampled pointer that fits for primary to a 'native' sample pointer
141 * freqAccNext is used here rather than freqAcc: In case the app wants to fill up to
142 * the play position it won't overwrite it
144 static DWORD DSOUND_bufpos_to_secpos(const IDirectSoundBufferImpl *dsb, DWORD bufpos)
146 DWORD oAdv = dsb->device->pwfx->nBlockAlign, iAdv = dsb->pwfx->nBlockAlign, pos;
147 DWORD64 framelen;
148 DWORD64 acc;
150 framelen = bufpos/oAdv;
151 acc = framelen * (DWORD64)dsb->freqAdjust + (DWORD64)dsb->freqAccNext;
152 acc = acc >> DSOUND_FREQSHIFT;
153 pos = (DWORD)acc * iAdv;
154 if (pos >= dsb->buflen)
155 /* Because of differences between freqAcc and freqAccNext, this might happen */
156 pos = dsb->buflen - iAdv;
157 TRACE("Converted %d/%d to %d/%d\n", bufpos, dsb->tmp_buffer_len, pos, dsb->buflen);
158 return pos;
162 * Move freqAccNext to freqAcc, and find new values for buffer length and freqAccNext
164 static void DSOUND_RecalcFreqAcc(IDirectSoundBufferImpl *dsb)
166 if (!dsb->freqneeded) return;
167 dsb->freqAcc = dsb->freqAccNext;
168 dsb->tmp_buffer_len = DSOUND_secpos_to_bufpos(dsb, dsb->buflen, 0, &dsb->freqAccNext);
169 TRACE("New freqadjust: %04x, new buflen: %d\n", dsb->freqAccNext, dsb->tmp_buffer_len);
173 * Recalculate the size for temporary buffer, and new writelead
174 * Should be called when one of the following things occur:
175 * - Primary buffer format is changed
176 * - This buffer format (frequency) is changed
178 * After this, DSOUND_MixToTemporary(dsb, 0, dsb->buflen) should
179 * be called to refill the temporary buffer with data.
181 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
183 BOOL needremix = TRUE, needresample = (dsb->freq != dsb->device->pwfx->nSamplesPerSec);
184 DWORD bAlign = dsb->pwfx->nBlockAlign, pAlign = dsb->device->pwfx->nBlockAlign;
185 WAVEFORMATEXTENSIBLE *pwfxe;
186 BOOL ieee = FALSE;
188 TRACE("(%p)\n",dsb);
190 pwfxe = (WAVEFORMATEXTENSIBLE *) dsb->pwfx;
192 if ((pwfxe->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) || ((pwfxe->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE)
193 && (IsEqualGUID(&pwfxe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))))
194 ieee = TRUE;
196 /* calculate the 10ms write lead */
197 dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
199 if ((dsb->pwfx->wBitsPerSample == dsb->device->pwfx->wBitsPerSample) &&
200 (dsb->pwfx->nChannels == dsb->device->pwfx->nChannels) && !needresample && !ieee)
201 needremix = FALSE;
202 HeapFree(GetProcessHeap(), 0, dsb->tmp_buffer);
203 dsb->tmp_buffer = NULL;
204 dsb->max_buffer_len = dsb->freqAcc = dsb->freqAccNext = 0;
205 dsb->freqneeded = needresample;
207 if (ieee)
208 dsb->convert = convertbpp[4][dsb->device->pwfx->wBitsPerSample/8 - 1];
209 else
210 dsb->convert = convertbpp[dsb->pwfx->wBitsPerSample/8 - 1][dsb->device->pwfx->wBitsPerSample/8 - 1];
212 dsb->resampleinmixer = FALSE;
214 if (needremix)
216 if (needresample)
217 DSOUND_RecalcFreqAcc(dsb);
218 else
219 dsb->tmp_buffer_len = dsb->buflen / bAlign * pAlign;
220 dsb->max_buffer_len = dsb->tmp_buffer_len;
221 if ((dsb->max_buffer_len <= dsb->device->buflen || dsb->max_buffer_len < ds_snd_shadow_maxsize * 1024 * 1024) && ds_snd_shadow_maxsize >= 0)
222 dsb->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, dsb->max_buffer_len);
223 if (dsb->tmp_buffer)
224 FillMemory(dsb->tmp_buffer, dsb->tmp_buffer_len, dsb->device->pwfx->wBitsPerSample == 8 ? 128 : 0);
225 else
226 dsb->resampleinmixer = TRUE;
228 else dsb->max_buffer_len = dsb->tmp_buffer_len = dsb->buflen;
229 dsb->buf_mixpos = DSOUND_secpos_to_bufpos(dsb, dsb->sec_mixpos, 0, NULL);
233 * Check for application callback requests for when the play position
234 * reaches certain points.
236 * The offsets that will be triggered will be those between the recorded
237 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
238 * beyond that position.
240 void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
242 int i;
243 DWORD offset;
244 LPDSBPOSITIONNOTIFY event;
245 TRACE("(%p,%d)\n",dsb,len);
247 if (dsb->nrofnotifies == 0)
248 return;
250 TRACE("(%p) buflen = %d, playpos = %d, len = %d\n",
251 dsb, dsb->buflen, playpos, len);
252 for (i = 0; i < dsb->nrofnotifies ; i++) {
253 event = dsb->notifies + i;
254 offset = event->dwOffset;
255 TRACE("checking %d, position %d, event = %p\n",
256 i, offset, event->hEventNotify);
257 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
258 /* OK. [Inside DirectX, p274] */
259 /* Windows does not seem to enforce this, and some apps rely */
260 /* on that, so we can't stop there. */
261 /* */
262 /* This also means we can't sort the entries by offset, */
263 /* because DSBPN_OFFSETSTOP == -1 */
264 if (offset == DSBPN_OFFSETSTOP) {
265 if (dsb->state == STATE_STOPPED) {
266 SetEvent(event->hEventNotify);
267 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
269 continue;
271 if ((playpos + len) >= dsb->buflen) {
272 if ((offset < ((playpos + len) % dsb->buflen)) ||
273 (offset >= playpos)) {
274 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
275 SetEvent(event->hEventNotify);
277 } else {
278 if ((offset >= playpos) && (offset < (playpos + len))) {
279 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
280 SetEvent(event->hEventNotify);
287 * Copy a single frame from the given input buffer to the given output buffer.
288 * Translate 8 <-> 16 bits and mono <-> stereo
290 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, const BYTE *ibuf, BYTE *obuf,
291 UINT istride, UINT ostride, UINT count, UINT freqAcc, UINT adj)
293 DirectSoundDevice *device = dsb->device;
294 INT istep = dsb->pwfx->wBitsPerSample / 8, ostep = device->pwfx->wBitsPerSample / 8;
296 if (device->pwfx->nChannels == dsb->pwfx->nChannels ||
297 (device->pwfx->nChannels == 2 && dsb->pwfx->nChannels == 6) ||
298 (device->pwfx->nChannels == 8 && dsb->pwfx->nChannels == 2) ||
299 (device->pwfx->nChannels == 6 && dsb->pwfx->nChannels == 2)) {
300 dsb->convert(ibuf, obuf, istride, ostride, count, freqAcc, adj);
301 if (device->pwfx->nChannels == 2 || dsb->pwfx->nChannels == 2)
302 dsb->convert(ibuf + istep, obuf + ostep, istride, ostride, count, freqAcc, adj);
303 return;
306 if (device->pwfx->nChannels == 1 && dsb->pwfx->nChannels == 2)
308 dsb->convert(ibuf, obuf, istride, ostride, count, freqAcc, adj);
309 return;
312 if (device->pwfx->nChannels == 2 && dsb->pwfx->nChannels == 1)
314 dsb->convert(ibuf, obuf, istride, ostride, count, freqAcc, adj);
315 dsb->convert(ibuf, obuf + ostep, istride, ostride, count, freqAcc, adj);
316 return;
319 WARN("Unable to remap channels: device=%u, buffer=%u\n", device->pwfx->nChannels,
320 dsb->pwfx->nChannels);
324 * Calculate the distance between two buffer offsets, taking wraparound
325 * into account.
327 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
329 /* If these asserts fail, the problem is not here, but in the underlying code */
330 assert(ptr1 < buflen);
331 assert(ptr2 < buflen);
332 if (ptr1 >= ptr2) {
333 return ptr1 - ptr2;
334 } else {
335 return buflen + ptr1 - ptr2;
339 * Mix at most the given amount of data into the allocated temporary buffer
340 * of the given secondary buffer, starting from the dsb's first currently
341 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
342 * and bits-per-sample so that it is ideal for the primary buffer.
343 * Doesn't perform any mixing - this is a straight copy/convert operation.
345 * dsb = the secondary buffer
346 * writepos = Starting position of changed buffer
347 * len = number of bytes to resample from writepos
349 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
351 void DSOUND_MixToTemporary(const IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len, BOOL inmixer)
353 INT size;
354 BYTE *ibp, *obp, *obp_begin;
355 INT iAdvance = dsb->pwfx->nBlockAlign;
356 INT oAdvance = dsb->device->pwfx->nBlockAlign;
357 DWORD freqAcc, target_writepos = 0, overshot, maxlen;
359 /* We resample only when needed */
360 if ((dsb->tmp_buffer && inmixer) || (!dsb->tmp_buffer && !inmixer) || dsb->resampleinmixer != inmixer)
361 return;
363 assert(writepos + len <= dsb->buflen);
364 if (inmixer && writepos + len < dsb->buflen)
365 len += dsb->pwfx->nBlockAlign;
367 maxlen = DSOUND_secpos_to_bufpos(dsb, len, 0, NULL);
369 ibp = dsb->buffer->memory + writepos;
370 if (!inmixer)
371 obp_begin = dsb->tmp_buffer;
372 else if (dsb->device->tmp_buffer_len < maxlen || !dsb->device->tmp_buffer)
374 dsb->device->tmp_buffer_len = maxlen;
375 if (dsb->device->tmp_buffer)
376 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, maxlen);
377 else
378 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, maxlen);
379 obp_begin = dsb->device->tmp_buffer;
381 else
382 obp_begin = dsb->device->tmp_buffer;
384 TRACE("(%p, %p)\n", dsb, ibp);
385 size = len / iAdvance;
387 /* Check for same sample rate */
388 if (dsb->freq == dsb->device->pwfx->nSamplesPerSec) {
389 TRACE("(%p) Same sample rate %d = primary %d\n", dsb,
390 dsb->freq, dsb->device->pwfx->nSamplesPerSec);
391 obp = obp_begin;
392 if (!inmixer)
393 obp += writepos/iAdvance*oAdvance;
395 cp_fields(dsb, ibp, obp, iAdvance, oAdvance, size, 0, 1 << DSOUND_FREQSHIFT);
396 return;
399 /* Mix in different sample rates */
400 TRACE("(%p) Adjusting frequency: %d -> %d\n", dsb, dsb->freq, dsb->device->pwfx->nSamplesPerSec);
402 target_writepos = DSOUND_secpos_to_bufpos(dsb, writepos, dsb->sec_mixpos, &freqAcc);
403 overshot = freqAcc >> DSOUND_FREQSHIFT;
404 if (overshot)
406 if (overshot >= size)
407 return;
408 size -= overshot;
409 writepos += overshot * iAdvance;
410 if (writepos >= dsb->buflen)
411 return;
412 ibp = dsb->buffer->memory + writepos;
413 freqAcc &= (1 << DSOUND_FREQSHIFT) - 1;
414 TRACE("Overshot: %d, freqAcc: %04x\n", overshot, freqAcc);
417 if (!inmixer)
418 obp = obp_begin + target_writepos;
419 else obp = obp_begin;
421 /* FIXME: Small problem here when we're overwriting buf_mixpos, it then STILL uses old freqAcc, not sure if it matters or not */
422 cp_fields(dsb, ibp, obp, iAdvance, oAdvance, size, freqAcc, dsb->freqAdjust);
425 /** Apply volume to the given soundbuffer from (primary) position writepos and length len
426 * Returns: NULL if no volume needs to be applied
427 * or else a memory handle that holds 'len' volume adjusted buffer */
428 static LPBYTE DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT len)
430 INT i;
431 BYTE *bpc;
432 INT16 *bps, *mems;
433 DWORD vLeft, vRight;
434 INT nChannels = dsb->device->pwfx->nChannels;
435 LPBYTE mem = (dsb->tmp_buffer ? dsb->tmp_buffer : dsb->buffer->memory) + dsb->buf_mixpos;
437 if (dsb->resampleinmixer)
438 mem = dsb->device->tmp_buffer;
440 TRACE("(%p,%d)\n",dsb,len);
441 TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalLeftAmpFactor,
442 dsb->volpan.dwTotalRightAmpFactor);
444 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
445 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
446 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
447 return NULL; /* Nothing to do */
449 if (nChannels != 1 && nChannels != 2)
451 FIXME("There is no support for %d channels\n", nChannels);
452 return NULL;
455 if (dsb->device->pwfx->wBitsPerSample != 8 && dsb->device->pwfx->wBitsPerSample != 16)
457 FIXME("There is no support for %d bpp\n", dsb->device->pwfx->wBitsPerSample);
458 return NULL;
461 if (dsb->device->tmp_buffer_len < len || !dsb->device->tmp_buffer)
463 /* If we just resampled in DSOUND_MixToTemporary, we shouldn't need to resize here */
464 assert(!dsb->resampleinmixer);
465 dsb->device->tmp_buffer_len = len;
466 if (dsb->device->tmp_buffer)
467 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, len);
468 else
469 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
472 bpc = dsb->device->tmp_buffer;
473 bps = (INT16 *)bpc;
474 mems = (INT16 *)mem;
475 vLeft = dsb->volpan.dwTotalLeftAmpFactor;
476 if (nChannels > 1)
477 vRight = dsb->volpan.dwTotalRightAmpFactor;
478 else
479 vRight = vLeft;
481 switch (dsb->device->pwfx->wBitsPerSample) {
482 case 8:
483 /* 8-bit WAV is unsigned, but we need to operate */
484 /* on signed data for this to work properly */
485 for (i = 0; i < len-1; i+=2) {
486 *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
487 *(bpc++) = (((*(mem++) - 128) * vRight) >> 16) + 128;
489 if (len % 2 == 1 && nChannels == 1)
490 *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
491 break;
492 case 16:
493 /* 16-bit WAV is signed -- much better */
494 for (i = 0; i < len-3; i += 4) {
495 *(bps++) = (*(mems++) * vLeft) >> 16;
496 *(bps++) = (*(mems++) * vRight) >> 16;
498 if (len % 4 == 2 && nChannels == 1)
499 *(bps++) = ((INT)*(mems++) * vLeft) >> 16;
500 break;
502 return dsb->device->tmp_buffer;
506 * Mix (at most) the given number of bytes into the given position of the
507 * device buffer, from the secondary buffer "dsb" (starting at the current
508 * mix position for that buffer).
510 * Returns the number of bytes actually mixed into the device buffer. This
511 * will match fraglen unless the end of the secondary buffer is reached
512 * (and it is not looping).
514 * dsb = the secondary buffer to mix from
515 * writepos = position (offset) in device buffer to write at
516 * fraglen = number of bytes to mix
518 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
520 INT len = fraglen, ilen;
521 BYTE *ibuf = (dsb->tmp_buffer ? dsb->tmp_buffer : dsb->buffer->memory) + dsb->buf_mixpos, *volbuf;
522 DWORD oldpos, mixbufpos;
524 TRACE("buf_mixpos=%d/%d sec_mixpos=%d/%d\n", dsb->buf_mixpos, dsb->tmp_buffer_len, dsb->sec_mixpos, dsb->buflen);
525 TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
527 assert(dsb->buf_mixpos + len <= dsb->tmp_buffer_len);
529 if (len % dsb->device->pwfx->nBlockAlign) {
530 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
531 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
532 len -= len % nBlockAlign; /* data alignment */
535 /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
536 DSOUND_MixToTemporary(dsb, dsb->sec_mixpos, DSOUND_bufpos_to_secpos(dsb, dsb->buf_mixpos+len) - dsb->sec_mixpos, TRUE);
537 if (dsb->resampleinmixer)
538 ibuf = dsb->device->tmp_buffer;
540 /* Apply volume if needed */
541 volbuf = DSOUND_MixerVol(dsb, len);
542 if (volbuf)
543 ibuf = volbuf;
545 mixbufpos = DSOUND_bufpos_to_mixpos(dsb->device, writepos);
546 /* Now mix the temporary buffer into the devices main buffer */
547 if ((writepos + len) <= dsb->device->buflen)
548 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, len);
549 else
551 DWORD todo = dsb->device->buflen - writepos;
552 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, todo);
553 dsb->device->mixfunction(ibuf + todo, dsb->device->mix_buffer, len - todo);
556 oldpos = dsb->sec_mixpos;
557 dsb->buf_mixpos += len;
559 if (dsb->buf_mixpos >= dsb->tmp_buffer_len) {
560 if (dsb->buf_mixpos > dsb->tmp_buffer_len)
561 ERR("Mixpos (%u) past buflen (%u), capping...\n", dsb->buf_mixpos, dsb->tmp_buffer_len);
562 if (dsb->playflags & DSBPLAY_LOOPING) {
563 dsb->buf_mixpos -= dsb->tmp_buffer_len;
564 } else if (dsb->buf_mixpos >= dsb->tmp_buffer_len) {
565 dsb->buf_mixpos = dsb->sec_mixpos = 0;
566 dsb->state = STATE_STOPPED;
568 DSOUND_RecalcFreqAcc(dsb);
571 dsb->sec_mixpos = DSOUND_bufpos_to_secpos(dsb, dsb->buf_mixpos);
572 ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
573 /* check for notification positions */
574 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
575 dsb->state != STATE_STARTING) {
576 DSOUND_CheckEvent(dsb, oldpos, ilen);
579 /* increase mix position */
580 dsb->primary_mixpos += len;
581 if (dsb->primary_mixpos >= dsb->device->buflen)
582 dsb->primary_mixpos -= dsb->device->buflen;
583 return len;
587 * Mix some frames from the given secondary buffer "dsb" into the device
588 * primary buffer.
590 * dsb = the secondary buffer
591 * playpos = the current play position in the device buffer (primary buffer)
592 * writepos = the current safe-to-write position in the device buffer
593 * mixlen = the maximum number of bytes in the primary buffer to mix, from the
594 * current writepos.
596 * Returns: the number of bytes beyond the writepos that were mixed.
598 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD mixlen)
600 /* The buffer's primary_mixpos may be before or after the device
601 * buffer's mixpos, but both must be ahead of writepos. */
602 DWORD primary_done;
604 TRACE("(%p,%d,%d)\n",dsb,writepos,mixlen);
605 TRACE("writepos=%d, buf_mixpos=%d, primary_mixpos=%d, mixlen=%d\n", writepos, dsb->buf_mixpos, dsb->primary_mixpos, mixlen);
606 TRACE("looping=%d, leadin=%d, buflen=%d\n", dsb->playflags, dsb->leadin, dsb->tmp_buffer_len);
608 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
609 if (dsb->leadin && dsb->state == STATE_STARTING)
611 if (mixlen > 2 * dsb->device->fraglen)
613 dsb->primary_mixpos += mixlen - 2 * dsb->device->fraglen;
614 dsb->primary_mixpos %= dsb->device->buflen;
617 dsb->leadin = FALSE;
619 /* calculate how much pre-buffering has already been done for this buffer */
620 primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
622 /* sanity */
623 if(mixlen < primary_done)
625 /* Should *NEVER* happen */
626 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);
627 dsb->primary_mixpos = writepos + mixlen;
628 dsb->primary_mixpos %= dsb->device->buflen;
629 return mixlen;
632 /* take into account already mixed data */
633 mixlen -= primary_done;
635 TRACE("primary_done=%d, mixlen (primary) = %i\n", primary_done, mixlen);
637 if (!mixlen)
638 return primary_done;
640 /* First try to mix to the end of the buffer if possible
641 * Theoretically it would allow for better optimization
643 if (mixlen + dsb->buf_mixpos >= dsb->tmp_buffer_len)
645 DWORD newmixed, mixfirst = dsb->tmp_buffer_len - dsb->buf_mixpos;
646 newmixed = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixfirst);
647 mixlen -= newmixed;
649 if (dsb->playflags & DSBPLAY_LOOPING)
650 while (newmixed && mixlen)
652 mixfirst = (dsb->tmp_buffer_len < mixlen ? dsb->tmp_buffer_len : mixlen);
653 newmixed = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixfirst);
654 mixlen -= newmixed;
657 else DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixlen);
659 /* re-calculate the primary done */
660 primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
662 TRACE("new primary_mixpos=%d, total mixed data=%d\n", dsb->primary_mixpos, primary_done);
664 /* Report back the total prebuffered amount for this buffer */
665 return primary_done;
669 * For a DirectSoundDevice, go through all the currently playing buffers and
670 * mix them in to the device buffer.
672 * writepos = the current safe-to-write position in the primary buffer
673 * mixlen = the maximum amount to mix into the primary buffer
674 * (beyond the current writepos)
675 * recover = true if the sound device may have been reset and the write
676 * position in the device buffer changed
677 * all_stopped = reports back if all buffers have stopped
679 * Returns: the length beyond the writepos that was mixed to.
682 static DWORD DSOUND_MixToPrimary(const DirectSoundDevice *device, DWORD writepos, DWORD mixlen, BOOL recover, BOOL *all_stopped)
684 INT i, len;
685 DWORD minlen = 0;
686 IDirectSoundBufferImpl *dsb;
688 /* unless we find a running buffer, all have stopped */
689 *all_stopped = TRUE;
691 TRACE("(%d,%d,%d)\n", writepos, mixlen, recover);
692 for (i = 0; i < device->nrofbuffers; i++) {
693 dsb = device->buffers[i];
695 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
697 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
698 TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
699 RtlAcquireResourceShared(&dsb->lock, TRUE);
700 /* if buffer is stopping it is stopped now */
701 if (dsb->state == STATE_STOPPING) {
702 dsb->state = STATE_STOPPED;
703 DSOUND_CheckEvent(dsb, 0, 0);
704 } else if (dsb->state != STATE_STOPPED) {
706 /* if recovering, reset the mix position */
707 if ((dsb->state == STATE_STARTING) || recover) {
708 dsb->primary_mixpos = writepos;
711 /* if the buffer was starting, it must be playing now */
712 if (dsb->state == STATE_STARTING)
713 dsb->state = STATE_PLAYING;
715 /* mix next buffer into the main buffer */
716 len = DSOUND_MixOne(dsb, writepos, mixlen);
718 if (!minlen) minlen = len;
720 /* record the minimum length mixed from all buffers */
721 /* we only want to return the length which *all* buffers have mixed */
722 else if (len) minlen = (len < minlen) ? len : minlen;
724 *all_stopped = FALSE;
726 RtlReleaseResource(&dsb->lock);
730 TRACE("Mixed at least %d from all buffers\n", minlen);
731 return minlen;
735 * Add buffers to the emulated wave device system.
737 * device = The current dsound playback device
738 * force = If TRUE, the function will buffer up as many frags as possible,
739 * even though and will ignore the actual state of the primary buffer.
741 * Returns: None
744 static void DSOUND_WaveQueue(DirectSoundDevice *device, BOOL force)
746 DWORD prebuf_frags, wave_writepos, wave_fragpos, i;
747 TRACE("(%p)\n", device);
749 /* calculate the current wave frag position */
750 wave_fragpos = (device->pwplay + device->pwqueue) % device->helfrags;
752 /* calculate the current wave write position */
753 wave_writepos = wave_fragpos * device->fraglen;
755 TRACE("wave_fragpos = %i, wave_writepos = %i, pwqueue = %i, prebuf = %i\n",
756 wave_fragpos, wave_writepos, device->pwqueue, device->prebuf);
758 if (!force)
760 /* check remaining prebuffered frags */
761 prebuf_frags = device->mixpos / device->fraglen;
762 if (prebuf_frags == device->helfrags)
763 --prebuf_frags;
764 TRACE("wave_fragpos = %d, mixpos_frags = %d\n", wave_fragpos, prebuf_frags);
765 if (prebuf_frags < wave_fragpos)
766 prebuf_frags += device->helfrags;
767 prebuf_frags -= wave_fragpos;
768 TRACE("wanted prebuf_frags = %d\n", prebuf_frags);
770 else
771 /* buffer the maximum amount of frags */
772 prebuf_frags = device->prebuf;
774 /* limit to the queue we have left */
775 if ((prebuf_frags + device->pwqueue) > device->prebuf)
776 prebuf_frags = device->prebuf - device->pwqueue;
778 TRACE("prebuf_frags = %i\n", prebuf_frags);
780 /* adjust queue */
781 device->pwqueue += prebuf_frags;
783 /* get out of CS when calling the wave system */
784 LeaveCriticalSection(&(device->mixlock));
785 /* **** */
787 /* queue up the new buffers */
788 for(i=0; i<prebuf_frags; i++){
789 TRACE("queueing wave buffer %i\n", wave_fragpos);
790 waveOutWrite(device->hwo, &device->pwave[wave_fragpos], sizeof(WAVEHDR));
791 wave_fragpos++;
792 wave_fragpos %= device->helfrags;
795 /* **** */
796 EnterCriticalSection(&(device->mixlock));
798 TRACE("queue now = %i\n", device->pwqueue);
802 * Perform mixing for a Direct Sound device. That is, go through all the
803 * secondary buffers (the sound bites currently playing) and mix them in
804 * to the primary buffer (the device buffer).
806 static void DSOUND_PerformMix(DirectSoundDevice *device)
808 TRACE("(%p)\n", device);
810 /* **** */
811 EnterCriticalSection(&(device->mixlock));
813 if (device->priolevel != DSSCL_WRITEPRIMARY) {
814 BOOL recover = FALSE, all_stopped = FALSE;
815 DWORD playpos, writepos, writelead, maxq, frag, prebuff_max, prebuff_left, size1, size2, mixplaypos, mixplaypos2;
816 LPVOID buf1, buf2;
817 BOOL lock = (device->hwbuf && !(device->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK));
818 int nfiller;
820 /* the sound of silence */
821 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
823 /* get the position in the primary buffer */
824 if (DSOUND_PrimaryGetPosition(device, &playpos, &writepos) != 0){
825 LeaveCriticalSection(&(device->mixlock));
826 return;
829 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
830 playpos,writepos,device->playpos,device->mixpos,device->buflen);
831 assert(device->playpos < device->buflen);
833 mixplaypos = DSOUND_bufpos_to_mixpos(device, device->playpos);
834 mixplaypos2 = DSOUND_bufpos_to_mixpos(device, playpos);
836 /* calc maximum prebuff */
837 prebuff_max = (device->prebuf * device->fraglen);
838 if (!device->hwbuf && playpos + prebuff_max >= device->helfrags * device->fraglen)
839 prebuff_max += device->buflen - device->helfrags * device->fraglen;
841 /* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
842 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
843 writelead = DSOUND_BufPtrDiff(device->buflen, writepos, playpos);
845 /* check for underrun. underrun occurs when the write position passes the mix position
846 * also wipe out just-played sound data */
847 if((prebuff_left > prebuff_max) || (device->state == STATE_STOPPED) || (device->state == STATE_STARTING)){
848 if (device->state == STATE_STOPPING || device->state == STATE_PLAYING)
849 WARN("Probable buffer underrun\n");
850 else TRACE("Buffer starting or buffer underrun\n");
852 /* recover mixing for all buffers */
853 recover = TRUE;
855 /* reset mix position to write position */
856 device->mixpos = writepos;
858 ZeroMemory(device->mix_buffer, device->mix_buffer_len);
859 ZeroMemory(device->buffer, device->buflen);
860 } else if (playpos < device->playpos) {
861 buf1 = device->buffer + device->playpos;
862 buf2 = device->buffer;
863 size1 = device->buflen - device->playpos;
864 size2 = playpos;
865 FillMemory(device->mix_buffer + mixplaypos, device->mix_buffer_len - mixplaypos, 0);
866 FillMemory(device->mix_buffer, mixplaypos2, 0);
867 if (lock)
868 IDsDriverBuffer_Lock(device->hwbuf, &buf1, &size1, &buf2, &size2, device->playpos, size1+size2, 0);
869 FillMemory(buf1, size1, nfiller);
870 if (playpos && (!buf2 || !size2))
871 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__, device->playpos, device->mixpos, playpos, writepos);
872 FillMemory(buf2, size2, nfiller);
873 if (lock)
874 IDsDriverBuffer_Unlock(device->hwbuf, buf1, size1, buf2, size2);
875 } else {
876 buf1 = device->buffer + device->playpos;
877 buf2 = NULL;
878 size1 = playpos - device->playpos;
879 size2 = 0;
880 FillMemory(device->mix_buffer + mixplaypos, mixplaypos2 - mixplaypos, 0);
881 if (lock)
882 IDsDriverBuffer_Lock(device->hwbuf, &buf1, &size1, &buf2, &size2, device->playpos, size1+size2, 0);
883 FillMemory(buf1, size1, nfiller);
884 if (buf2 && size2)
886 FIXME("%d: There should be no additional buffer here!!\n", __LINE__);
887 FillMemory(buf2, size2, nfiller);
889 if (lock)
890 IDsDriverBuffer_Unlock(device->hwbuf, buf1, size1, buf2, size2);
892 device->playpos = playpos;
894 /* find the maximum we can prebuffer from current write position */
895 maxq = (writelead < prebuff_max) ? (prebuff_max - writelead) : 0;
897 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
898 prebuff_left, device->prebuf, device->fraglen, prebuff_max, writelead);
900 if (lock)
901 IDsDriverBuffer_Lock(device->hwbuf, &buf1, &size1, &buf2, &size2, writepos, maxq, 0);
903 /* do the mixing */
904 frag = DSOUND_MixToPrimary(device, writepos, maxq, recover, &all_stopped);
906 if (frag + writepos > device->buflen)
908 DWORD todo = device->buflen - writepos;
909 device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, todo);
910 device->normfunction(device->mix_buffer, device->buffer, frag - todo);
912 else
913 device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, frag);
915 /* update the mix position, taking wrap-around into account */
916 device->mixpos = writepos + frag;
917 device->mixpos %= device->buflen;
919 if (lock)
921 DWORD frag2 = (frag > size1 ? frag - size1 : 0);
922 frag -= frag2;
923 if (frag2 > size2)
925 FIXME("Buffering too much! (%d, %d, %d, %d)\n", maxq, frag, size2, frag2 - size2);
926 frag2 = size2;
928 IDsDriverBuffer_Unlock(device->hwbuf, buf1, frag, buf2, frag2);
931 /* update prebuff left */
932 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
934 /* check if have a whole fragment */
935 if (prebuff_left >= device->fraglen){
937 /* update the wave queue if using wave system */
938 if (!device->hwbuf)
939 DSOUND_WaveQueue(device, FALSE);
941 /* buffers are full. start playing if applicable */
942 if(device->state == STATE_STARTING){
943 TRACE("started primary buffer\n");
944 if(DSOUND_PrimaryPlay(device) != DS_OK){
945 WARN("DSOUND_PrimaryPlay failed\n");
947 else{
948 /* we are playing now */
949 device->state = STATE_PLAYING;
953 /* buffers are full. start stopping if applicable */
954 if(device->state == STATE_STOPPED){
955 TRACE("restarting primary buffer\n");
956 if(DSOUND_PrimaryPlay(device) != DS_OK){
957 WARN("DSOUND_PrimaryPlay failed\n");
959 else{
960 /* start stopping again. as soon as there is no more data, it will stop */
961 device->state = STATE_STOPPING;
966 /* if device was stopping, its for sure stopped when all buffers have stopped */
967 else if((all_stopped == TRUE) && (device->state == STATE_STOPPING)){
968 TRACE("All buffers have stopped. Stopping primary buffer\n");
969 device->state = STATE_STOPPED;
971 /* stop the primary buffer now */
972 DSOUND_PrimaryStop(device);
975 } else {
977 /* update the wave queue if using wave system */
978 if (!device->hwbuf)
979 DSOUND_WaveQueue(device, TRUE);
980 else
981 /* Keep alsa happy, which needs GetPosition called once every 10 ms */
982 IDsDriverBuffer_GetPosition(device->hwbuf, NULL, NULL);
984 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
985 if (device->state == STATE_STARTING) {
986 if (DSOUND_PrimaryPlay(device) != DS_OK)
987 WARN("DSOUND_PrimaryPlay failed\n");
988 else
989 device->state = STATE_PLAYING;
991 else if (device->state == STATE_STOPPING) {
992 if (DSOUND_PrimaryStop(device) != DS_OK)
993 WARN("DSOUND_PrimaryStop failed\n");
994 else
995 device->state = STATE_STOPPED;
999 LeaveCriticalSection(&(device->mixlock));
1000 /* **** */
1003 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD_PTR dwUser,
1004 DWORD_PTR dw1, DWORD_PTR dw2)
1006 DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
1007 DWORD start_time = GetTickCount();
1008 DWORD end_time;
1009 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
1010 TRACE("entering at %d\n", start_time);
1012 if (DSOUND_renderer[device->drvdesc.dnDevNode] != device) {
1013 ERR("dsound died without killing us?\n");
1014 timeKillEvent(timerID);
1015 timeEndPeriod(DS_TIME_RES);
1016 return;
1019 RtlAcquireResourceShared(&(device->buffer_list_lock), TRUE);
1021 if (device->ref)
1022 DSOUND_PerformMix(device);
1024 RtlReleaseResource(&(device->buffer_list_lock));
1026 end_time = GetTickCount();
1027 TRACE("completed processing at %d, duration = %d\n", end_time, end_time - start_time);
1030 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1032 DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
1033 TRACE("(%p,%x,%lx,%lx,%lx)\n",hwo,msg,dwUser,dw1,dw2);
1034 TRACE("entering at %d, msg=%08x(%s)\n", GetTickCount(), msg,
1035 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
1036 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1038 /* check if packet completed from wave driver */
1039 if (msg == MM_WOM_DONE) {
1041 /* **** */
1042 EnterCriticalSection(&(device->mixlock));
1044 TRACE("done playing primary pos=%d\n", device->pwplay * device->fraglen);
1046 /* update playpos */
1047 device->pwplay++;
1048 device->pwplay %= device->helfrags;
1050 /* sanity */
1051 if(device->pwqueue == 0){
1052 ERR("Wave queue corrupted!\n");
1055 /* update queue */
1056 device->pwqueue--;
1058 LeaveCriticalSection(&(device->mixlock));
1059 /* **** */
1061 TRACE("completed\n");