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
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include <math.h> /* Insomnia - pow() function */
28 #define NONAMELESSSTRUCT
29 #define NONAMELESSUNION
35 #include "wine/debug.h"
38 #include "dsound_private.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
42 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
45 TRACE("(%p)\n",volpan);
47 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
48 /* the AmpFactors are expressed in 16.16 fixed point */
49 volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
50 /* FIXME: dwPan{Left|Right}AmpFactor */
52 /* FIXME: use calculated vol and pan ampfactors */
53 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
54 volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
55 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
56 volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
58 TRACE("left = %x, right = %x\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
61 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
64 TRACE("(%p)\n",volpan);
66 TRACE("left=%x, right=%x\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
67 if (volpan->dwTotalLeftAmpFactor==0)
70 left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
71 if (volpan->dwTotalRightAmpFactor==0)
74 right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
77 volpan->lVolume=right;
78 volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
83 volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
85 if (volpan->lVolume < -10000)
86 volpan->lVolume=-10000;
87 volpan->lPan=right-left;
88 if (volpan->lPan < -10000)
91 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
94 /* NOTE: Not all secpos have to always be mapped to a bufpos, other way around is always the case
95 * DWORD64 is used here because a single DWORD wouldn't be big enough to fit the freqAcc for big buffers
97 /** This function converts a 'native' sample pointer to a resampled pointer that fits for primary
98 * secmixpos is used to decide which freqAcc is needed
99 * overshot tells what the 'actual' secpos is now (optional)
101 DWORD DSOUND_secpos_to_bufpos(const IDirectSoundBufferImpl *dsb, DWORD secpos, DWORD secmixpos, DWORD* overshot)
103 DWORD64 framelen = secpos / dsb->pwfx->nBlockAlign;
104 DWORD64 freqAdjust = dsb->freqAdjust;
105 DWORD64 acc, freqAcc;
107 if (secpos < secmixpos)
108 freqAcc = dsb->freqAccNext;
109 else freqAcc = dsb->freqAcc;
110 acc = (framelen << DSOUND_FREQSHIFT) + (freqAdjust - 1 - freqAcc);
114 DWORD64 oshot = acc * freqAdjust + freqAcc;
115 assert(oshot >= framelen << DSOUND_FREQSHIFT);
116 oshot -= framelen << DSOUND_FREQSHIFT;
117 *overshot = (DWORD)oshot;
118 assert(*overshot < dsb->freqAdjust);
120 return (DWORD)acc * dsb->device->pwfx->nBlockAlign;
123 /** Convert a resampled pointer that fits for primary to a 'native' sample pointer
124 * freqAccNext is used here rather than freqAcc: In case the app wants to fill up to
125 * the play position it won't overwrite it
127 static DWORD DSOUND_bufpos_to_secpos(const IDirectSoundBufferImpl *dsb, DWORD bufpos)
129 DWORD oAdv = dsb->device->pwfx->nBlockAlign, iAdv = dsb->pwfx->nBlockAlign, pos;
133 framelen = bufpos/oAdv;
134 acc = framelen * (DWORD64)dsb->freqAdjust + (DWORD64)dsb->freqAccNext;
135 acc = acc >> DSOUND_FREQSHIFT;
136 pos = (DWORD)acc * iAdv;
137 if (pos >= dsb->buflen)
138 /* Because of differences between freqAcc and freqAccNext, this might happen */
139 pos = dsb->buflen - iAdv;
140 TRACE("Converted %d/%d to %d/%d\n", bufpos, dsb->tmp_buffer_len, pos, dsb->buflen);
145 * Move freqAccNext to freqAcc, and find new values for buffer length and freqAccNext
147 static void DSOUND_RecalcFreqAcc(IDirectSoundBufferImpl *dsb)
149 if (!dsb->freqneeded) return;
150 dsb->freqAcc = dsb->freqAccNext;
151 dsb->tmp_buffer_len = DSOUND_secpos_to_bufpos(dsb, dsb->buflen, 0, &dsb->freqAccNext);
152 TRACE("New freqadjust: %04x, new buflen: %d\n", dsb->freqAccNext, dsb->tmp_buffer_len);
156 * Recalculate the size for temporary buffer, and new writelead
157 * Should be called when one of the following things occur:
158 * - Primary buffer format is changed
159 * - This buffer format (frequency) is changed
161 * After this, DSOUND_MixToTemporary(dsb, 0, dsb->buflen) should
162 * be called to refill the temporary buffer with data.
164 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
166 BOOL needremix = TRUE, needresample = (dsb->freq != dsb->device->pwfx->nSamplesPerSec);
167 DWORD bAlign = dsb->pwfx->nBlockAlign, pAlign = dsb->device->pwfx->nBlockAlign;
171 /* calculate the 10ms write lead */
172 dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
174 if ((dsb->pwfx->wBitsPerSample == dsb->device->pwfx->wBitsPerSample) &&
175 (dsb->pwfx->nChannels == dsb->device->pwfx->nChannels) && !needresample)
177 HeapFree(GetProcessHeap(), 0, dsb->tmp_buffer);
178 dsb->tmp_buffer = NULL;
179 dsb->max_buffer_len = dsb->freqAcc = dsb->freqAccNext = 0;
180 dsb->freqneeded = needresample;
185 DSOUND_RecalcFreqAcc(dsb);
187 dsb->tmp_buffer_len = dsb->buflen / bAlign * pAlign;
188 dsb->max_buffer_len = dsb->tmp_buffer_len;
189 dsb->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, dsb->max_buffer_len);
190 FillMemory(dsb->tmp_buffer, dsb->tmp_buffer_len, dsb->device->pwfx->wBitsPerSample == 8 ? 128 : 0);
192 else dsb->max_buffer_len = dsb->tmp_buffer_len = dsb->buflen;
193 dsb->buf_mixpos = DSOUND_secpos_to_bufpos(dsb, dsb->sec_mixpos, 0, NULL);
197 * Check for application callback requests for when the play position
198 * reaches certain points.
200 * The offsets that will be triggered will be those between the recorded
201 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
202 * beyond that position.
204 void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
208 LPDSBPOSITIONNOTIFY event;
209 TRACE("(%p,%d)\n",dsb,len);
211 if (dsb->nrofnotifies == 0)
214 TRACE("(%p) buflen = %d, playpos = %d, len = %d\n",
215 dsb, dsb->buflen, playpos, len);
216 for (i = 0; i < dsb->nrofnotifies ; i++) {
217 event = dsb->notifies + i;
218 offset = event->dwOffset;
219 TRACE("checking %d, position %d, event = %p\n",
220 i, offset, event->hEventNotify);
221 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
222 /* OK. [Inside DirectX, p274] */
224 /* This also means we can't sort the entries by offset, */
225 /* because DSBPN_OFFSETSTOP == -1 */
226 if (offset == DSBPN_OFFSETSTOP) {
227 if (dsb->state == STATE_STOPPED) {
228 SetEvent(event->hEventNotify);
229 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
234 if ((playpos + len) >= dsb->buflen) {
235 if ((offset < ((playpos + len) % dsb->buflen)) ||
236 (offset >= playpos)) {
237 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
238 SetEvent(event->hEventNotify);
241 if ((offset >= playpos) && (offset < (playpos + len))) {
242 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
243 SetEvent(event->hEventNotify);
249 /* WAV format info can be found at:
251 * http://www.cwi.nl/ftp/audio/AudioFormats.part2
252 * ftp://ftp.cwi.nl/pub/audio/RIFF-format
254 * Import points to remember:
255 * 8-bit WAV is unsigned
256 * 16-bit WAV is signed
258 /* Use the same formulas as pcmconverter.c */
259 static inline INT16 cvtU8toS16(BYTE b)
261 return (short)((b+(b << 8))-32768);
264 static inline BYTE cvtS16toU8(INT16 s)
266 return (s >> 8) ^ (unsigned char)0x80;
270 * Copy a single frame from the given input buffer to the given output buffer.
271 * Translate 8 <-> 16 bits and mono <-> stereo
273 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, const BYTE *ibuf, BYTE *obuf )
275 DirectSoundDevice * device = dsb->device;
278 if (dsb->pwfx->wBitsPerSample == 8) {
279 if (device->pwfx->wBitsPerSample == 8 &&
280 device->pwfx->nChannels == dsb->pwfx->nChannels) {
281 /* avoid needless 8->16->8 conversion */
283 if (dsb->pwfx->nChannels==2)
287 fl = cvtU8toS16(*ibuf);
288 fr = (dsb->pwfx->nChannels==2 ? cvtU8toS16(*(ibuf + 1)) : fl);
290 fl = *((const INT16 *)ibuf);
291 fr = (dsb->pwfx->nChannels==2 ? *(((const INT16 *)ibuf) + 1) : fl);
294 if (device->pwfx->nChannels == 2) {
295 if (device->pwfx->wBitsPerSample == 8) {
296 *obuf = cvtS16toU8(fl);
297 *(obuf + 1) = cvtS16toU8(fr);
300 if (device->pwfx->wBitsPerSample == 16) {
301 *((INT16 *)obuf) = fl;
302 *(((INT16 *)obuf) + 1) = fr;
306 if (device->pwfx->nChannels == 1) {
308 if (device->pwfx->wBitsPerSample == 8) {
309 *obuf = cvtS16toU8(fl);
312 if (device->pwfx->wBitsPerSample == 16) {
313 *((INT16 *)obuf) = fl;
320 * Calculate the distance between two buffer offsets, taking wraparound
323 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
325 /* If these asserts fail, the problem is not here, but in the underlying code */
326 assert(ptr1 < buflen);
327 assert(ptr2 < buflen);
331 return buflen + ptr1 - ptr2;
335 * Mix at most the given amount of data into the allocated temporary buffer
336 * of the given secondary buffer, starting from the dsb's first currently
337 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
338 * and bits-per-sample so that it is ideal for the primary buffer.
339 * Doesn't perform any mixing - this is a straight copy/convert operation.
341 * dsb = the secondary buffer
342 * writepos = Starting position of changed buffer
343 * len = number of bytes to resample from writepos
345 * NOTE: writepos + len <= buflen, This function doesn't loop!
347 void DSOUND_MixToTemporary(const IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len)
350 BYTE *ibp, *obp, *ibp_begin, *obp_begin;
351 INT iAdvance = dsb->pwfx->nBlockAlign;
352 INT oAdvance = dsb->device->pwfx->nBlockAlign;
353 DWORD freqAcc, target_writepos, overshot;
355 if (!dsb->tmp_buffer)
356 /* Nothing to do, already ideal format */
359 ibp = dsb->buffer->memory + writepos;
360 ibp_begin = dsb->buffer->memory;
361 obp_begin = dsb->tmp_buffer;
363 TRACE("(%p, %p)\n", dsb, ibp);
364 /* Check for the best case */
365 if ((dsb->freq == dsb->device->pwfx->nSamplesPerSec) &&
366 (dsb->pwfx->wBitsPerSample == dsb->device->pwfx->wBitsPerSample) &&
367 (dsb->pwfx->nChannels == dsb->device->pwfx->nChannels)) {
368 obp = dsb->tmp_buffer + writepos;
369 /* Why would we need a temporary buffer if we do best case? */
370 FIXME("(%p) Why do we resample for best case??? Bad!!\n", dsb);
371 CopyMemory(obp, ibp, len);
375 /* Check for same sample rate */
376 if (dsb->freq == dsb->device->pwfx->nSamplesPerSec) {
377 TRACE("(%p) Same sample rate %d = primary %d\n", dsb,
378 dsb->freq, dsb->device->pwfx->nSamplesPerSec);
379 obp = dsb->tmp_buffer + writepos/iAdvance*oAdvance;
380 for (i = 0; i < len; i += iAdvance) {
381 cp_fields(dsb, ibp, obp);
388 /* Mix in different sample rates */
389 TRACE("(%p) Adjusting frequency: %d -> %d\n", dsb, dsb->freq, dsb->device->pwfx->nSamplesPerSec);
390 size = len / iAdvance;
392 target_writepos = DSOUND_secpos_to_bufpos(dsb, writepos, dsb->sec_mixpos, &freqAcc);
393 overshot = freqAcc >> DSOUND_FREQSHIFT;
396 if (overshot >= size)
399 writepos += overshot * iAdvance;
400 if (writepos >= dsb->buflen)
402 ibp = dsb->buffer->memory + writepos;
403 freqAcc &= (1 << DSOUND_FREQSHIFT) - 1;
404 TRACE("Overshot: %d, freqAcc: %04x\n", overshot, freqAcc);
407 obp = dsb->tmp_buffer + target_writepos;
408 /* FIXME: Small problem here when we're overwriting buf_mixpos, it then STILL uses old freqAcc, not sure if it matters or not */
410 cp_fields(dsb, ibp, obp);
412 freqAcc += dsb->freqAdjust;
413 if (freqAcc >= (1<<DSOUND_FREQSHIFT)) {
414 ULONG adv = (freqAcc>>DSOUND_FREQSHIFT);
415 freqAcc &= (1<<DSOUND_FREQSHIFT)-1;
416 ibp += adv * iAdvance;
422 /** Apply volume to the given soundbuffer from (primary) position writepos and length len
423 * Returns: NULL if no volume needs to be applied
424 * or else a memory handle that holds 'len' volume adjusted buffer */
425 static LPBYTE DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, DWORD writepos, INT len)
431 INT nChannels = dsb->device->pwfx->nChannels;
432 LPBYTE mem = (dsb->tmp_buffer ? dsb->tmp_buffer : dsb->buffer->memory)+writepos;
434 TRACE("(%p,%d)\n",dsb,len);
435 TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalLeftAmpFactor,
436 dsb->volpan.dwTotalRightAmpFactor);
438 if (nChannels != 1 && nChannels != 2)
440 FIXME("There is no support for %d channels\n", nChannels);
444 if (dsb->device->pwfx->wBitsPerSample != 8 && dsb->device->pwfx->wBitsPerSample != 16)
446 FIXME("There is no support for %d bpp\n", dsb->device->pwfx->wBitsPerSample);
450 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
451 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
452 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
453 return NULL; /* Nothing to do */
455 if (dsb->device->tmp_buffer_len < len || !dsb->device->tmp_buffer)
457 dsb->device->tmp_buffer_len = len;
458 if (dsb->device->tmp_buffer)
459 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, len);
461 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
463 bpc = dsb->device->tmp_buffer;
466 vLeft = dsb->volpan.dwTotalLeftAmpFactor;
468 vRight = dsb->volpan.dwTotalRightAmpFactor;
472 switch (dsb->device->pwfx->wBitsPerSample) {
474 /* 8-bit WAV is unsigned, but we need to operate */
475 /* on signed data for this to work properly */
476 for (i = 0; i < len; i+=2) {
477 *(bpc++) = (((INT)(*(mem++) - 128) * vLeft) >> 16) + 128;
478 *(bpc++) = (((INT)(*(mem++) - 128) * vRight) >> 16) + 128;
480 if (len % 2 == 1 && nChannels == 1)
481 *(bpc++) = (((INT)(*(mem++) - 128) * vLeft) >> 16) + 128;
484 /* 16-bit WAV is signed -- much better */
485 for (i = 0; i < len; i += 4) {
486 *(bps++) = (*(mems++) * vLeft) >> 16;
487 *(bps++) = (*(mems++) * vRight) >> 16;
489 if (len % 4 == 2 && nChannels == 1)
490 *(bps++) = ((INT)*(mems++) * vLeft) >> 16;
493 return dsb->device->tmp_buffer;
497 * Mix (at most) the given number of bytes into the given position of the
498 * device buffer, from the secondary buffer "dsb" (starting at the current
499 * mix position for that buffer).
501 * Returns the number of bytes actually mixed into the device buffer. This
502 * will match fraglen unless the end of the secondary buffer is reached
503 * (and it is not looping).
505 * dsb = the secondary buffer to mix from
506 * writepos = position (offset) in device buffer to write at
507 * fraglen = number of bytes to mix
509 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
511 INT i, len = fraglen, field, todo, ilen;
512 BYTE *ibuf = (dsb->tmp_buffer ? dsb->tmp_buffer : dsb->buffer->memory) + dsb->buf_mixpos, *volbuf;
515 TRACE("buf_mixpos=%d/%d sec_mixpos=%d/%d\n", dsb->buf_mixpos, dsb->tmp_buffer_len, dsb->sec_mixpos, dsb->buflen);
516 TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
518 assert(dsb->buf_mixpos + len <= dsb->tmp_buffer_len);
520 if (len % dsb->device->pwfx->nBlockAlign) {
521 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
522 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
523 len -= len % nBlockAlign; /* data alignment */
526 /* Apply volume if needed */
527 volbuf = DSOUND_MixerVol(dsb, dsb->buf_mixpos, len);
531 /* Now mix the temporary buffer into the devices main buffer */
532 if (dsb->device->pwfx->wBitsPerSample == 8) {
533 BYTE *obuf = dsb->device->buffer + writepos;
535 if ((writepos + len) <= dsb->device->buflen)
538 todo = dsb->device->buflen - writepos;
540 for (i = 0; i < todo; i++) {
541 /* 8-bit WAV is unsigned */
542 field = (*ibuf++ - 128);
543 field += (*obuf - 128);
544 if (field > 127) field = 127;
545 else if (field < -128) field = -128;
546 *obuf++ = field + 128;
551 obuf = dsb->device->buffer;
553 for (i = 0; i < todo; i++) {
554 /* 8-bit WAV is unsigned */
555 field = (*ibuf++ - 128);
556 field += (*obuf - 128);
557 if (field > 127) field = 127;
558 else if (field < -128) field = -128;
559 *obuf++ = field + 128;
563 INT16 *ibufs, *obufs;
565 ibufs = (INT16 *) ibuf;
566 obufs = (INT16 *)(dsb->device->buffer + writepos);
568 if ((writepos + len) <= dsb->device->buflen)
571 todo = (dsb->device->buflen - writepos) / 2;
573 for (i = 0; i < todo; i++) {
574 /* 16-bit WAV is signed */
578 if (field > 32767) field = 32767;
579 else if (field < -32768) field = -32768;
583 if (todo < (len / 2)) {
584 todo = (len / 2) - todo;
585 obufs = (INT16 *)dsb->device->buffer;
587 for (i = 0; i < todo; i++) {
588 /* 16-bit WAV is signed */
591 if (field > 32767) field = 32767;
592 else if (field < -32768) field = -32768;
598 oldpos = dsb->sec_mixpos;
599 dsb->buf_mixpos += len;
601 if (dsb->buf_mixpos >= dsb->tmp_buffer_len) {
602 if (dsb->playflags & DSBPLAY_LOOPING) {
603 dsb->buf_mixpos -= dsb->tmp_buffer_len;
604 } else if (dsb->buf_mixpos >= dsb->tmp_buffer_len) {
605 if (dsb->buf_mixpos > dsb->tmp_buffer_len)
606 ERR("Mixpos (%u) past buflen (%u), capping...\n", dsb->buf_mixpos, dsb->tmp_buffer_len);
607 dsb->buf_mixpos = dsb->sec_mixpos = 0;
608 dsb->state = STATE_STOPPED;
610 DSOUND_RecalcFreqAcc(dsb);
613 dsb->sec_mixpos = DSOUND_bufpos_to_secpos(dsb, dsb->buf_mixpos);
614 ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
615 /* check for notification positions */
616 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
617 dsb->state != STATE_STARTING) {
618 DSOUND_CheckEvent(dsb, oldpos, ilen);
621 /* increase mix position */
622 dsb->primary_mixpos += len;
623 if (dsb->primary_mixpos >= dsb->device->buflen)
624 dsb->primary_mixpos -= dsb->device->buflen;
629 * Mix some frames from the given secondary buffer "dsb" into the device
632 * dsb = the secondary buffer
633 * playpos = the current play position in the device buffer (primary buffer)
634 * writepos = the current safe-to-write position in the device buffer
635 * mixlen = the maximum number of bytes in the primary buffer to mix, from the
638 * Returns: the number of bytes beyond the writepos that were mixed.
640 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD mixlen)
642 /* The buffer's primary_mixpos may be before or after the the device
643 * buffer's mixpos, but both must be ahead of writepos. */
646 TRACE("(%p,%d,%d)\n",dsb,writepos,mixlen);
647 TRACE("writepos=%d, buf_mixpos=%d, primary_mixpos=%d, mixlen=%d\n", writepos, dsb->buf_mixpos, dsb->primary_mixpos, mixlen);
648 TRACE("looping=%d, leadin=%d, buflen=%d\n", dsb->playflags, dsb->leadin, dsb->tmp_buffer_len);
650 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
651 if (dsb->leadin && dsb->state == STATE_STARTING)
653 if (mixlen > 2 * dsb->device->fraglen)
655 dsb->primary_mixpos += mixlen - 2 * dsb->device->fraglen;
656 dsb->primary_mixpos %= dsb->device->buflen;
661 /* calculate how much pre-buffering has already been done for this buffer */
662 primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
665 if(mixlen < primary_done)
667 /* Should *NEVER* happen */
668 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);
672 /* take into acount already mixed data */
673 mixlen -= primary_done;
675 TRACE("primary_done=%d, mixlen (primary) = %i\n", primary_done, mixlen);
680 /* First try to mix to the end of the buffer if possible
681 * Theoretically it would allow for better optimization
683 if (mixlen + dsb->buf_mixpos >= dsb->tmp_buffer_len)
685 DWORD newmixed, mixfirst = dsb->tmp_buffer_len - dsb->buf_mixpos;
686 newmixed = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixfirst);
689 if (dsb->playflags & DSBPLAY_LOOPING)
690 while (newmixed && mixlen)
692 mixfirst = (dsb->tmp_buffer_len < mixlen ? dsb->tmp_buffer_len : mixlen);
693 newmixed = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixfirst);
697 else DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixlen);
699 /* re-calculate the primary done */
700 primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
702 TRACE("new primary_mixpos=%d, total mixed data=%d\n", dsb->primary_mixpos, primary_done);
704 /* Report back the total prebuffered amount for this buffer */
709 * For a DirectSoundDevice, go through all the currently playing buffers and
710 * mix them in to the device buffer.
712 * writepos = the current safe-to-write position in the primary buffer
713 * mixlen = the maximum amount to mix into the primary buffer
714 * (beyond the current writepos)
715 * mustlock = Do we have to fight for lock because we otherwise risk an underrun?
716 * recover = true if the sound device may have been reset and the write
717 * position in the device buffer changed
718 * all_stopped = reports back if all buffers have stopped
720 * Returns: the length beyond the writepos that was mixed to.
723 static DWORD DSOUND_MixToPrimary(const DirectSoundDevice *device, DWORD writepos, DWORD mixlen, BOOL mustlock, BOOL recover, BOOL *all_stopped)
727 IDirectSoundBufferImpl *dsb;
730 /* unless we find a running buffer, all have stopped */
733 TRACE("(%d,%d,%d)\n", writepos, mixlen, recover);
734 for (i = 0; i < device->nrofbuffers; i++) {
735 dsb = device->buffers[i];
737 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
739 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
740 TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
741 if (!RtlAcquireResourceShared(&dsb->lock, mustlock))
746 /* if buffer is stopping it is stopped now */
747 if (dsb->state == STATE_STOPPING) {
748 dsb->state = STATE_STOPPED;
749 DSOUND_CheckEvent(dsb, 0, 0);
750 } else if (dsb->state != STATE_STOPPED) {
752 /* if recovering, reset the mix position */
753 if ((dsb->state == STATE_STARTING) || recover) {
754 dsb->primary_mixpos = writepos;
757 /* mix next buffer into the main buffer */
758 len = DSOUND_MixOne(dsb, writepos, mixlen);
760 /* if the buffer was starting, it must be playing now */
761 if (dsb->state == STATE_STARTING)
762 dsb->state = STATE_PLAYING;
764 if (!minlen) minlen = len;
766 /* record the minimum length mixed from all buffers */
767 /* we only want to return the length which *all* buffers have mixed */
768 else if (len) minlen = (len < minlen) ? len : minlen;
770 *all_stopped = FALSE;
772 RtlReleaseResource(&dsb->lock);
776 TRACE("Mixed at least %d from all buffers\n", minlen);
777 if (!gotall) return 0;
782 * Add buffers to the emulated wave device system.
784 * device = The current dsound playback device
785 * force = If TRUE, the function will buffer up as many frags as possible,
786 * even though and will ignore the actual state of the primary buffer.
791 static void DSOUND_WaveQueue(DirectSoundDevice *device, BOOL force)
793 DWORD prebuf_frags, wave_writepos, wave_fragpos, i;
794 TRACE("(%p)\n", device);
796 /* calculate the current wave frag position */
797 wave_fragpos = (device->pwplay + device->pwqueue) % device->helfrags;
799 /* calculte the current wave write position */
800 wave_writepos = wave_fragpos * device->fraglen;
802 TRACE("wave_fragpos = %i, wave_writepos = %i, pwqueue = %i, prebuf = %i\n",
803 wave_fragpos, wave_writepos, device->pwqueue, device->prebuf);
806 /* check remaining prebuffered frags */
807 prebuf_frags = DSOUND_BufPtrDiff(device->buflen, device->mixpos, wave_writepos);
808 prebuf_frags = prebuf_frags / device->fraglen;
811 /* buffer the maximum amount of frags */
812 prebuf_frags = device->prebuf;
815 /* limit to the queue we have left */
816 if((prebuf_frags + device->pwqueue) > device->prebuf)
817 prebuf_frags = device->prebuf - device->pwqueue;
819 TRACE("prebuf_frags = %i\n", prebuf_frags);
822 device->pwqueue += prebuf_frags;
824 /* get out of CS when calling the wave system */
825 LeaveCriticalSection(&(device->mixlock));
828 /* queue up the new buffers */
829 for(i=0; i<prebuf_frags; i++){
830 TRACE("queueing wave buffer %i\n", wave_fragpos);
831 waveOutWrite(device->hwo, &device->pwave[wave_fragpos], sizeof(WAVEHDR));
833 wave_fragpos %= device->helfrags;
837 EnterCriticalSection(&(device->mixlock));
839 TRACE("queue now = %i\n", device->pwqueue);
843 * Perform mixing for a Direct Sound device. That is, go through all the
844 * secondary buffers (the sound bites currently playing) and mix them in
845 * to the primary buffer (the device buffer).
847 static void DSOUND_PerformMix(DirectSoundDevice *device)
850 TRACE("(%p)\n", device);
853 EnterCriticalSection(&(device->mixlock));
855 if (device->priolevel != DSSCL_WRITEPRIMARY) {
856 BOOL recover = FALSE, all_stopped = FALSE;
857 DWORD playpos, writepos, writelead, maxq, frag, prebuff_max, prebuff_left, size1, size2;
859 BOOL lock = (device->hwbuf && !(device->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK));
860 BOOL mustlock = FALSE;
863 /* the sound of silence */
864 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
866 /* get the position in the primary buffer */
867 if (DSOUND_PrimaryGetPosition(device, &playpos, &writepos) != 0){
868 LeaveCriticalSection(&(device->mixlock));
872 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
873 playpos,writepos,device->playpos,device->mixpos,device->buflen);
874 assert(device->playpos < device->buflen);
876 /* wipe out just-played sound data */
877 if (playpos < device->playpos) {
878 buf1 = device->buffer + device->playpos;
879 buf2 = device->buffer;
880 size1 = device->buflen - device->playpos;
883 IDsDriverBuffer_Lock(device->hwbuf, &buf1, &size1, &buf2, &size2, device->playpos, size1+size2, 0);
884 FillMemory(buf1, size1, nfiller);
885 if (playpos && (!buf2 || !size2))
886 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__, device->playpos, device->mixpos, playpos, writepos);
887 FillMemory(buf2, size2, nfiller);
889 IDsDriverBuffer_Unlock(device->hwbuf, buf1, size1, buf2, size2);
891 buf1 = device->buffer + device->playpos;
893 size1 = playpos - device->playpos;
896 IDsDriverBuffer_Lock(device->hwbuf, &buf1, &size1, &buf2, &size2, device->playpos, size1+size2, 0);
897 FillMemory(buf1, size1, nfiller);
900 FIXME("%d: There should be no additional buffer here!!\n", __LINE__);
901 FillMemory(buf2, size2, nfiller);
904 IDsDriverBuffer_Unlock(device->hwbuf, buf1, size1, buf2, size2);
906 device->playpos = playpos;
908 /* calc maximum prebuff */
909 prebuff_max = (device->prebuf * device->fraglen);
911 /* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
912 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
913 writelead = DSOUND_BufPtrDiff(device->buflen, writepos, playpos);
915 /* find the maximum we can prebuffer from current write position */
916 maxq = (writelead < prebuff_max) ? (prebuff_max - writelead) : 0;
918 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
919 prebuff_left, device->prebuf, device->fraglen, prebuff_max, writelead);
921 /* check for underrun. underrun occurs when the write position passes the mix position */
922 if((prebuff_left > prebuff_max) || (device->state == STATE_STOPPED) || (device->state == STATE_STARTING)){
923 if (device->state == STATE_STOPPING || device->state == STATE_PLAYING)
924 WARN("Probable buffer underrun\n");
925 else TRACE("Buffer starting or buffer underrun\n");
927 /* recover mixing for all buffers */
930 /* reset mix position to write position */
931 device->mixpos = writepos;
934 /* Do we risk an 'underrun' if we don't advance pointer? */
935 if (writelead/device->fraglen <= ds_snd_queue_min || recover)
939 IDsDriverBuffer_Lock(device->hwbuf, &buf1, &size1, &buf2, &size2, writepos, maxq, 0);
942 frag = DSOUND_MixToPrimary(device, writepos, maxq, mustlock, recover, &all_stopped);
944 /* update the mix position, taking wrap-around into acount */
945 device->mixpos = writepos + frag;
946 device->mixpos %= device->buflen;
950 DWORD frag2 = (frag > size1 ? frag - size1 : 0);
954 FIXME("Buffering too much! (%d, %d, %d, %d)\n", maxq, frag, size2, frag2 - size2);
957 IDsDriverBuffer_Unlock(device->hwbuf, buf1, frag, buf2, frag2);
960 /* update prebuff left */
961 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
963 /* check if have a whole fragment */
964 if (prebuff_left >= device->fraglen){
966 /* update the wave queue if using wave system */
967 if(device->hwbuf == NULL){
968 DSOUND_WaveQueue(device,TRUE);
971 /* buffers are full. start playing if applicable */
972 if(device->state == STATE_STARTING){
973 TRACE("started primary buffer\n");
974 if(DSOUND_PrimaryPlay(device) != DS_OK){
975 WARN("DSOUND_PrimaryPlay failed\n");
978 /* we are playing now */
979 device->state = STATE_PLAYING;
983 /* buffers are full. start stopping if applicable */
984 if(device->state == STATE_STOPPED){
985 TRACE("restarting primary buffer\n");
986 if(DSOUND_PrimaryPlay(device) != DS_OK){
987 WARN("DSOUND_PrimaryPlay failed\n");
990 /* start stopping again. as soon as there is no more data, it will stop */
991 device->state = STATE_STOPPING;
996 /* if device was stopping, its for sure stopped when all buffers have stopped */
997 else if((all_stopped == TRUE) && (device->state == STATE_STOPPING)){
998 TRACE("All buffers have stopped. Stopping primary buffer\n");
999 device->state = STATE_STOPPED;
1001 /* stop the primary buffer now */
1002 DSOUND_PrimaryStop(device);
1007 /* update the wave queue if using wave system */
1008 if(device->hwbuf == NULL)
1009 DSOUND_WaveQueue(device, TRUE);
1011 /* Keep alsa happy, which needs GetPosition called once every 10 ms */
1012 IDsDriverBuffer_GetPosition(device->hwbuf, NULL, NULL);
1014 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
1015 if (device->state == STATE_STARTING) {
1016 if (DSOUND_PrimaryPlay(device) != DS_OK)
1017 WARN("DSOUND_PrimaryPlay failed\n");
1019 device->state = STATE_PLAYING;
1021 else if (device->state == STATE_STOPPING) {
1022 if (DSOUND_PrimaryStop(device) != DS_OK)
1023 WARN("DSOUND_PrimaryStop failed\n");
1025 device->state = STATE_STOPPED;
1029 LeaveCriticalSection(&(device->mixlock));
1033 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD_PTR dwUser,
1034 DWORD_PTR dw1, DWORD_PTR dw2)
1036 DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
1037 DWORD start_time = GetTickCount();
1039 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
1040 TRACE("entering at %d\n", start_time);
1042 if (DSOUND_renderer[device->drvdesc.dnDevNode] != device) {
1043 ERR("dsound died without killing us?\n");
1044 timeKillEvent(timerID);
1045 timeEndPeriod(DS_TIME_RES);
1049 RtlAcquireResourceShared(&(device->buffer_list_lock), TRUE);
1052 DSOUND_PerformMix(device);
1054 RtlReleaseResource(&(device->buffer_list_lock));
1056 end_time = GetTickCount();
1057 TRACE("completed processing at %d, duration = %d\n", end_time, end_time - start_time);
1060 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
1062 DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
1063 TRACE("(%p,%x,%x,%x,%x)\n",hwo,msg,dwUser,dw1,dw2);
1064 TRACE("entering at %d, msg=%08x(%s)\n", GetTickCount(), msg,
1065 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
1066 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1068 /* check if packet completed from wave driver */
1069 if (msg == MM_WOM_DONE) {
1072 EnterCriticalSection(&(device->mixlock));
1074 TRACE("done playing primary pos=%d\n", device->pwplay * device->fraglen);
1076 /* update playpos */
1078 device->pwplay %= device->helfrags;
1081 if(device->pwqueue == 0){
1082 ERR("Wave queue corrupted!\n");
1088 LeaveCriticalSection(&(device->mixlock));
1091 TRACE("completed\n");