Sync with trunk (r48144)
[reactos.git] / dll / directx / dsound / mixer.c
1 /* DirectSound
2 *
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 *
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.
13 *
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.
18 *
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
22 */
23
24 #include <assert.h>
25 #include <stdarg.h>
26 #include <math.h> /* Insomnia - pow() function */
27
28 #define NONAMELESSSTRUCT
29 #define NONAMELESSUNION
30 #include "windef.h"
31 #include "winbase.h"
32 #include "mmsystem.h"
33 #include "winternl.h"
34 #include "wine/debug.h"
35 #include "dsound.h"
36 #include "dsdriver.h"
37 #include "dsound_private.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
40
41 void DSOUND_RecalcVolPan(PDSVOLUMEPAN volpan)
42 {
43 double temp;
44 TRACE("(%p)\n",volpan);
45
46 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
47 /* the AmpFactors are expressed in 16.16 fixed point */
48 volpan->dwVolAmpFactor = (ULONG) (pow(2.0, volpan->lVolume / 600.0) * 0xffff);
49 /* FIXME: dwPan{Left|Right}AmpFactor */
50
51 /* FIXME: use calculated vol and pan ampfactors */
52 temp = (double) (volpan->lVolume - (volpan->lPan > 0 ? volpan->lPan : 0));
53 volpan->dwTotalLeftAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
54 temp = (double) (volpan->lVolume + (volpan->lPan < 0 ? volpan->lPan : 0));
55 volpan->dwTotalRightAmpFactor = (ULONG) (pow(2.0, temp / 600.0) * 0xffff);
56
57 TRACE("left = %x, right = %x\n", volpan->dwTotalLeftAmpFactor, volpan->dwTotalRightAmpFactor);
58 }
59
60 void DSOUND_AmpFactorToVolPan(PDSVOLUMEPAN volpan)
61 {
62 double left,right;
63 TRACE("(%p)\n",volpan);
64
65 TRACE("left=%x, right=%x\n",volpan->dwTotalLeftAmpFactor,volpan->dwTotalRightAmpFactor);
66 if (volpan->dwTotalLeftAmpFactor==0)
67 left=-10000;
68 else
69 left=600 * log(((double)volpan->dwTotalLeftAmpFactor) / 0xffff) / log(2);
70 if (volpan->dwTotalRightAmpFactor==0)
71 right=-10000;
72 else
73 right=600 * log(((double)volpan->dwTotalRightAmpFactor) / 0xffff) / log(2);
74 if (left<right)
75 {
76 volpan->lVolume=right;
77 volpan->dwVolAmpFactor=volpan->dwTotalRightAmpFactor;
78 }
79 else
80 {
81 volpan->lVolume=left;
82 volpan->dwVolAmpFactor=volpan->dwTotalLeftAmpFactor;
83 }
84 if (volpan->lVolume < -10000)
85 volpan->lVolume=-10000;
86 volpan->lPan=right-left;
87 if (volpan->lPan < -10000)
88 volpan->lPan=-10000;
89
90 TRACE("Vol=%d Pan=%d\n", volpan->lVolume, volpan->lPan);
91 }
92
93 /** Convert a primary buffer position to a pointer position for device->mix_buffer
94 * device: DirectSoundDevice for which to calculate
95 * pos: Primary buffer position to converts
96 * Returns: Offset for mix_buffer
97 */
98 DWORD DSOUND_bufpos_to_mixpos(const DirectSoundDevice* device, DWORD pos)
99 {
100 DWORD ret = pos * 32 / device->pwfx->wBitsPerSample;
101 if (device->pwfx->wBitsPerSample == 32)
102 ret *= 2;
103 return ret;
104 }
105
106 /* NOTE: Not all secpos have to always be mapped to a bufpos, other way around is always the case
107 * DWORD64 is used here because a single DWORD wouldn't be big enough to fit the freqAcc for big buffers
108 */
109 /** This function converts a 'native' sample pointer to a resampled pointer that fits for primary
110 * secmixpos is used to decide which freqAcc is needed
111 * overshot tells what the 'actual' secpos is now (optional)
112 */
113 DWORD DSOUND_secpos_to_bufpos(const IDirectSoundBufferImpl *dsb, DWORD secpos, DWORD secmixpos, DWORD* overshot)
114 {
115 DWORD64 framelen = secpos / dsb->pwfx->nBlockAlign;
116 DWORD64 freqAdjust = dsb->freqAdjust;
117 DWORD64 acc, freqAcc;
118
119 if (secpos < secmixpos)
120 freqAcc = dsb->freqAccNext;
121 else freqAcc = dsb->freqAcc;
122 acc = (framelen << DSOUND_FREQSHIFT) + (freqAdjust - 1 - freqAcc);
123 acc /= freqAdjust;
124 if (overshot)
125 {
126 DWORD64 oshot = acc * freqAdjust + freqAcc;
127 assert(oshot >= framelen << DSOUND_FREQSHIFT);
128 oshot -= framelen << DSOUND_FREQSHIFT;
129 *overshot = (DWORD)oshot;
130 assert(*overshot < dsb->freqAdjust);
131 }
132 return (DWORD)acc * dsb->device->pwfx->nBlockAlign;
133 }
134
135 /** Convert a resampled pointer that fits for primary to a 'native' sample pointer
136 * freqAccNext is used here rather than freqAcc: In case the app wants to fill up to
137 * the play position it won't overwrite it
138 */
139 static DWORD DSOUND_bufpos_to_secpos(const IDirectSoundBufferImpl *dsb, DWORD bufpos)
140 {
141 DWORD oAdv = dsb->device->pwfx->nBlockAlign, iAdv = dsb->pwfx->nBlockAlign, pos;
142 DWORD64 framelen;
143 DWORD64 acc;
144
145 framelen = bufpos/oAdv;
146 acc = framelen * (DWORD64)dsb->freqAdjust + (DWORD64)dsb->freqAccNext;
147 acc = acc >> DSOUND_FREQSHIFT;
148 pos = (DWORD)acc * iAdv;
149 if (pos >= dsb->buflen)
150 /* Because of differences between freqAcc and freqAccNext, this might happen */
151 pos = dsb->buflen - iAdv;
152 TRACE("Converted %d/%d to %d/%d\n", bufpos, dsb->tmp_buffer_len, pos, dsb->buflen);
153 return pos;
154 }
155
156 /**
157 * Move freqAccNext to freqAcc, and find new values for buffer length and freqAccNext
158 */
159 static void DSOUND_RecalcFreqAcc(IDirectSoundBufferImpl *dsb)
160 {
161 if (!dsb->freqneeded) return;
162 dsb->freqAcc = dsb->freqAccNext;
163 dsb->tmp_buffer_len = DSOUND_secpos_to_bufpos(dsb, dsb->buflen, 0, &dsb->freqAccNext);
164 TRACE("New freqadjust: %04x, new buflen: %d\n", dsb->freqAccNext, dsb->tmp_buffer_len);
165 }
166
167 /**
168 * Recalculate the size for temporary buffer, and new writelead
169 * Should be called when one of the following things occur:
170 * - Primary buffer format is changed
171 * - This buffer format (frequency) is changed
172 *
173 * After this, DSOUND_MixToTemporary(dsb, 0, dsb->buflen) should
174 * be called to refill the temporary buffer with data.
175 */
176 void DSOUND_RecalcFormat(IDirectSoundBufferImpl *dsb)
177 {
178 BOOL needremix = TRUE, needresample = (dsb->freq != dsb->device->pwfx->nSamplesPerSec);
179 DWORD bAlign = dsb->pwfx->nBlockAlign, pAlign = dsb->device->pwfx->nBlockAlign;
180
181 TRACE("(%p)\n",dsb);
182
183 /* calculate the 10ms write lead */
184 dsb->writelead = (dsb->freq / 100) * dsb->pwfx->nBlockAlign;
185
186 if ((dsb->pwfx->wBitsPerSample == dsb->device->pwfx->wBitsPerSample) &&
187 (dsb->pwfx->nChannels == dsb->device->pwfx->nChannels) && !needresample)
188 needremix = FALSE;
189 HeapFree(GetProcessHeap(), 0, dsb->tmp_buffer);
190 dsb->tmp_buffer = NULL;
191 dsb->max_buffer_len = dsb->freqAcc = dsb->freqAccNext = 0;
192 dsb->freqneeded = needresample;
193
194 dsb->convert = convertbpp[dsb->pwfx->wBitsPerSample/8 - 1][dsb->device->pwfx->wBitsPerSample/8 - 1];
195
196 dsb->resampleinmixer = FALSE;
197
198 if (needremix)
199 {
200 if (needresample)
201 DSOUND_RecalcFreqAcc(dsb);
202 else
203 dsb->tmp_buffer_len = dsb->buflen / bAlign * pAlign;
204 dsb->max_buffer_len = dsb->tmp_buffer_len;
205 if ((dsb->max_buffer_len <= dsb->device->buflen || dsb->max_buffer_len < ds_snd_shadow_maxsize * 1024 * 1024) && ds_snd_shadow_maxsize >= 0)
206 dsb->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, dsb->max_buffer_len);
207 if (dsb->tmp_buffer)
208 FillMemory(dsb->tmp_buffer, dsb->tmp_buffer_len, dsb->device->pwfx->wBitsPerSample == 8 ? 128 : 0);
209 else
210 dsb->resampleinmixer = TRUE;
211 }
212 else dsb->max_buffer_len = dsb->tmp_buffer_len = dsb->buflen;
213 dsb->buf_mixpos = DSOUND_secpos_to_bufpos(dsb, dsb->sec_mixpos, 0, NULL);
214 }
215
216 /**
217 * Check for application callback requests for when the play position
218 * reaches certain points.
219 *
220 * The offsets that will be triggered will be those between the recorded
221 * "last played" position for the buffer (i.e. dsb->playpos) and "len" bytes
222 * beyond that position.
223 */
224 void DSOUND_CheckEvent(const IDirectSoundBufferImpl *dsb, DWORD playpos, int len)
225 {
226 int i;
227 DWORD offset;
228 LPDSBPOSITIONNOTIFY event;
229 TRACE("(%p,%d)\n",dsb,len);
230
231 if (dsb->nrofnotifies == 0)
232 return;
233
234 TRACE("(%p) buflen = %d, playpos = %d, len = %d\n",
235 dsb, dsb->buflen, playpos, len);
236 for (i = 0; i < dsb->nrofnotifies ; i++) {
237 event = dsb->notifies + i;
238 offset = event->dwOffset;
239 TRACE("checking %d, position %d, event = %p\n",
240 i, offset, event->hEventNotify);
241 /* DSBPN_OFFSETSTOP has to be the last element. So this is */
242 /* OK. [Inside DirectX, p274] */
243 /* Windows does not seem to enforce this, and some apps rely */
244 /* on that, so we can't stop there. */
245 /* */
246 /* This also means we can't sort the entries by offset, */
247 /* because DSBPN_OFFSETSTOP == -1 */
248 if (offset == DSBPN_OFFSETSTOP) {
249 if (dsb->state == STATE_STOPPED) {
250 SetEvent(event->hEventNotify);
251 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
252 }
253 continue;
254 }
255 if ((playpos + len) >= dsb->buflen) {
256 if ((offset < ((playpos + len) % dsb->buflen)) ||
257 (offset >= playpos)) {
258 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
259 SetEvent(event->hEventNotify);
260 }
261 } else {
262 if ((offset >= playpos) && (offset < (playpos + len))) {
263 TRACE("signalled event %p (%d)\n", event->hEventNotify, i);
264 SetEvent(event->hEventNotify);
265 }
266 }
267 }
268 }
269
270 /**
271 * Copy a single frame from the given input buffer to the given output buffer.
272 * Translate 8 <-> 16 bits and mono <-> stereo
273 */
274 static inline void cp_fields(const IDirectSoundBufferImpl *dsb, const BYTE *ibuf, BYTE *obuf,
275 UINT istride, UINT ostride, UINT count, UINT freqAcc, UINT adj)
276 {
277 DirectSoundDevice *device = dsb->device;
278 INT istep = dsb->pwfx->wBitsPerSample / 8, ostep = device->pwfx->wBitsPerSample / 8;
279
280 if (device->pwfx->nChannels == dsb->pwfx->nChannels) {
281 dsb->convert(ibuf, obuf, istride, ostride, count, freqAcc, adj);
282 if (device->pwfx->nChannels == 2)
283 dsb->convert(ibuf + istep, obuf + ostep, istride, ostride, count, freqAcc, adj);
284 }
285
286 if (device->pwfx->nChannels == 1 && dsb->pwfx->nChannels == 2)
287 {
288 dsb->convert(ibuf, obuf, istride, ostride, count, freqAcc, adj);
289 }
290
291 if (device->pwfx->nChannels == 2 && dsb->pwfx->nChannels == 1)
292 {
293 dsb->convert(ibuf, obuf, istride, ostride, count, freqAcc, adj);
294 dsb->convert(ibuf, obuf + ostep, istride, ostride, count, freqAcc, adj);
295 }
296 }
297
298 /**
299 * Calculate the distance between two buffer offsets, taking wraparound
300 * into account.
301 */
302 static inline DWORD DSOUND_BufPtrDiff(DWORD buflen, DWORD ptr1, DWORD ptr2)
303 {
304 /* If these asserts fail, the problem is not here, but in the underlying code */
305 assert(ptr1 < buflen);
306 assert(ptr2 < buflen);
307 if (ptr1 >= ptr2) {
308 return ptr1 - ptr2;
309 } else {
310 return buflen + ptr1 - ptr2;
311 }
312 }
313 /**
314 * Mix at most the given amount of data into the allocated temporary buffer
315 * of the given secondary buffer, starting from the dsb's first currently
316 * unsampled frame (writepos), translating frequency (pitch), stereo/mono
317 * and bits-per-sample so that it is ideal for the primary buffer.
318 * Doesn't perform any mixing - this is a straight copy/convert operation.
319 *
320 * dsb = the secondary buffer
321 * writepos = Starting position of changed buffer
322 * len = number of bytes to resample from writepos
323 *
324 * NOTE: writepos + len <= buflen. When called by mixer, MixOne makes sure of this.
325 */
326 void DSOUND_MixToTemporary(const IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD len, BOOL inmixer)
327 {
328 INT size;
329 BYTE *ibp, *obp, *obp_begin;
330 INT iAdvance = dsb->pwfx->nBlockAlign;
331 INT oAdvance = dsb->device->pwfx->nBlockAlign;
332 DWORD freqAcc, target_writepos = 0, overshot, maxlen;
333
334 /* We resample only when needed */
335 if ((dsb->tmp_buffer && inmixer) || (!dsb->tmp_buffer && !inmixer) || dsb->resampleinmixer != inmixer)
336 return;
337
338 assert(writepos + len <= dsb->buflen);
339 if (inmixer && writepos + len < dsb->buflen)
340 len += dsb->pwfx->nBlockAlign;
341
342 maxlen = DSOUND_secpos_to_bufpos(dsb, len, 0, NULL);
343
344 ibp = dsb->buffer->memory + writepos;
345 if (!inmixer)
346 obp_begin = dsb->tmp_buffer;
347 else if (dsb->device->tmp_buffer_len < maxlen || !dsb->device->tmp_buffer)
348 {
349 dsb->device->tmp_buffer_len = maxlen;
350 if (dsb->device->tmp_buffer)
351 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, maxlen);
352 else
353 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, maxlen);
354 obp_begin = dsb->device->tmp_buffer;
355 }
356 else
357 obp_begin = dsb->device->tmp_buffer;
358
359 TRACE("(%p, %p)\n", dsb, ibp);
360 size = len / iAdvance;
361
362 /* Check for same sample rate */
363 if (dsb->freq == dsb->device->pwfx->nSamplesPerSec) {
364 TRACE("(%p) Same sample rate %d = primary %d\n", dsb,
365 dsb->freq, dsb->device->pwfx->nSamplesPerSec);
366 obp = obp_begin;
367 if (!inmixer)
368 obp += writepos/iAdvance*oAdvance;
369
370 cp_fields(dsb, ibp, obp, iAdvance, oAdvance, size, 0, 1 << DSOUND_FREQSHIFT);
371 return;
372 }
373
374 /* Mix in different sample rates */
375 TRACE("(%p) Adjusting frequency: %d -> %d\n", dsb, dsb->freq, dsb->device->pwfx->nSamplesPerSec);
376
377 target_writepos = DSOUND_secpos_to_bufpos(dsb, writepos, dsb->sec_mixpos, &freqAcc);
378 overshot = freqAcc >> DSOUND_FREQSHIFT;
379 if (overshot)
380 {
381 if (overshot >= size)
382 return;
383 size -= overshot;
384 writepos += overshot * iAdvance;
385 if (writepos >= dsb->buflen)
386 return;
387 ibp = dsb->buffer->memory + writepos;
388 freqAcc &= (1 << DSOUND_FREQSHIFT) - 1;
389 TRACE("Overshot: %d, freqAcc: %04x\n", overshot, freqAcc);
390 }
391
392 if (!inmixer)
393 obp = obp_begin + target_writepos;
394 else obp = obp_begin;
395
396 /* FIXME: Small problem here when we're overwriting buf_mixpos, it then STILL uses old freqAcc, not sure if it matters or not */
397 cp_fields(dsb, ibp, obp, iAdvance, oAdvance, size, freqAcc, dsb->freqAdjust);
398 }
399
400 /** Apply volume to the given soundbuffer from (primary) position writepos and length len
401 * Returns: NULL if no volume needs to be applied
402 * or else a memory handle that holds 'len' volume adjusted buffer */
403 static LPBYTE DSOUND_MixerVol(const IDirectSoundBufferImpl *dsb, INT len)
404 {
405 INT i;
406 BYTE *bpc;
407 INT16 *bps, *mems;
408 DWORD vLeft, vRight;
409 INT nChannels = dsb->device->pwfx->nChannels;
410 LPBYTE mem = (dsb->tmp_buffer ? dsb->tmp_buffer : dsb->buffer->memory) + dsb->buf_mixpos;
411
412 if (dsb->resampleinmixer)
413 mem = dsb->device->tmp_buffer;
414
415 TRACE("(%p,%d)\n",dsb,len);
416 TRACE("left = %x, right = %x\n", dsb->volpan.dwTotalLeftAmpFactor,
417 dsb->volpan.dwTotalRightAmpFactor);
418
419 if ((!(dsb->dsbd.dwFlags & DSBCAPS_CTRLPAN) || (dsb->volpan.lPan == 0)) &&
420 (!(dsb->dsbd.dwFlags & DSBCAPS_CTRLVOLUME) || (dsb->volpan.lVolume == 0)) &&
421 !(dsb->dsbd.dwFlags & DSBCAPS_CTRL3D))
422 return NULL; /* Nothing to do */
423
424 if (nChannels != 1 && nChannels != 2)
425 {
426 FIXME("There is no support for %d channels\n", nChannels);
427 return NULL;
428 }
429
430 if (dsb->device->pwfx->wBitsPerSample != 8 && dsb->device->pwfx->wBitsPerSample != 16)
431 {
432 FIXME("There is no support for %d bpp\n", dsb->device->pwfx->wBitsPerSample);
433 return NULL;
434 }
435
436 if (dsb->device->tmp_buffer_len < len || !dsb->device->tmp_buffer)
437 {
438 /* If we just resampled in DSOUND_MixToTemporary, we shouldn't need to resize here */
439 assert(!dsb->resampleinmixer);
440 dsb->device->tmp_buffer_len = len;
441 if (dsb->device->tmp_buffer)
442 dsb->device->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0, dsb->device->tmp_buffer, len);
443 else
444 dsb->device->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, len);
445 }
446
447 bpc = dsb->device->tmp_buffer;
448 bps = (INT16 *)bpc;
449 mems = (INT16 *)mem;
450 vLeft = dsb->volpan.dwTotalLeftAmpFactor;
451 if (nChannels > 1)
452 vRight = dsb->volpan.dwTotalRightAmpFactor;
453 else
454 vRight = vLeft;
455
456 switch (dsb->device->pwfx->wBitsPerSample) {
457 case 8:
458 /* 8-bit WAV is unsigned, but we need to operate */
459 /* on signed data for this to work properly */
460 for (i = 0; i < len-1; i+=2) {
461 *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
462 *(bpc++) = (((*(mem++) - 128) * vRight) >> 16) + 128;
463 }
464 if (len % 2 == 1 && nChannels == 1)
465 *(bpc++) = (((*(mem++) - 128) * vLeft) >> 16) + 128;
466 break;
467 case 16:
468 /* 16-bit WAV is signed -- much better */
469 for (i = 0; i < len-3; i += 4) {
470 *(bps++) = (*(mems++) * vLeft) >> 16;
471 *(bps++) = (*(mems++) * vRight) >> 16;
472 }
473 if (len % 4 == 2 && nChannels == 1)
474 *(bps++) = ((INT)*(mems++) * vLeft) >> 16;
475 break;
476 }
477 return dsb->device->tmp_buffer;
478 }
479
480 /**
481 * Mix (at most) the given number of bytes into the given position of the
482 * device buffer, from the secondary buffer "dsb" (starting at the current
483 * mix position for that buffer).
484 *
485 * Returns the number of bytes actually mixed into the device buffer. This
486 * will match fraglen unless the end of the secondary buffer is reached
487 * (and it is not looping).
488 *
489 * dsb = the secondary buffer to mix from
490 * writepos = position (offset) in device buffer to write at
491 * fraglen = number of bytes to mix
492 */
493 static DWORD DSOUND_MixInBuffer(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD fraglen)
494 {
495 INT len = fraglen, ilen;
496 BYTE *ibuf = (dsb->tmp_buffer ? dsb->tmp_buffer : dsb->buffer->memory) + dsb->buf_mixpos, *volbuf;
497 DWORD oldpos, mixbufpos;
498
499 TRACE("buf_mixpos=%d/%d sec_mixpos=%d/%d\n", dsb->buf_mixpos, dsb->tmp_buffer_len, dsb->sec_mixpos, dsb->buflen);
500 TRACE("(%p,%d,%d)\n",dsb,writepos,fraglen);
501
502 assert(dsb->buf_mixpos + len <= dsb->tmp_buffer_len);
503
504 if (len % dsb->device->pwfx->nBlockAlign) {
505 INT nBlockAlign = dsb->device->pwfx->nBlockAlign;
506 ERR("length not a multiple of block size, len = %d, block size = %d\n", len, nBlockAlign);
507 len -= len % nBlockAlign; /* data alignment */
508 }
509
510 /* Resample buffer to temporary buffer specifically allocated for this purpose, if needed */
511 DSOUND_MixToTemporary(dsb, dsb->sec_mixpos, DSOUND_bufpos_to_secpos(dsb, dsb->buf_mixpos+len) - dsb->sec_mixpos, TRUE);
512 if (dsb->resampleinmixer)
513 ibuf = dsb->device->tmp_buffer;
514
515 /* Apply volume if needed */
516 volbuf = DSOUND_MixerVol(dsb, len);
517 if (volbuf)
518 ibuf = volbuf;
519
520 mixbufpos = DSOUND_bufpos_to_mixpos(dsb->device, writepos);
521 /* Now mix the temporary buffer into the devices main buffer */
522 if ((writepos + len) <= dsb->device->buflen)
523 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, len);
524 else
525 {
526 DWORD todo = dsb->device->buflen - writepos;
527 dsb->device->mixfunction(ibuf, dsb->device->mix_buffer + mixbufpos, todo);
528 dsb->device->mixfunction(ibuf + todo, dsb->device->mix_buffer, len - todo);
529 }
530
531 oldpos = dsb->sec_mixpos;
532 dsb->buf_mixpos += len;
533
534 if (dsb->buf_mixpos >= dsb->tmp_buffer_len) {
535 if (dsb->buf_mixpos > dsb->tmp_buffer_len)
536 ERR("Mixpos (%u) past buflen (%u), capping...\n", dsb->buf_mixpos, dsb->tmp_buffer_len);
537 if (dsb->playflags & DSBPLAY_LOOPING) {
538 dsb->buf_mixpos -= dsb->tmp_buffer_len;
539 } else if (dsb->buf_mixpos >= dsb->tmp_buffer_len) {
540 dsb->buf_mixpos = dsb->sec_mixpos = 0;
541 dsb->state = STATE_STOPPED;
542 }
543 DSOUND_RecalcFreqAcc(dsb);
544 }
545
546 dsb->sec_mixpos = DSOUND_bufpos_to_secpos(dsb, dsb->buf_mixpos);
547 ilen = DSOUND_BufPtrDiff(dsb->buflen, dsb->sec_mixpos, oldpos);
548 /* check for notification positions */
549 if (dsb->dsbd.dwFlags & DSBCAPS_CTRLPOSITIONNOTIFY &&
550 dsb->state != STATE_STARTING) {
551 DSOUND_CheckEvent(dsb, oldpos, ilen);
552 }
553
554 /* increase mix position */
555 dsb->primary_mixpos += len;
556 if (dsb->primary_mixpos >= dsb->device->buflen)
557 dsb->primary_mixpos -= dsb->device->buflen;
558 return len;
559 }
560
561 /**
562 * Mix some frames from the given secondary buffer "dsb" into the device
563 * primary buffer.
564 *
565 * dsb = the secondary buffer
566 * playpos = the current play position in the device buffer (primary buffer)
567 * writepos = the current safe-to-write position in the device buffer
568 * mixlen = the maximum number of bytes in the primary buffer to mix, from the
569 * current writepos.
570 *
571 * Returns: the number of bytes beyond the writepos that were mixed.
572 */
573 static DWORD DSOUND_MixOne(IDirectSoundBufferImpl *dsb, DWORD writepos, DWORD mixlen)
574 {
575 /* The buffer's primary_mixpos may be before or after the device
576 * buffer's mixpos, but both must be ahead of writepos. */
577 DWORD primary_done;
578
579 TRACE("(%p,%d,%d)\n",dsb,writepos,mixlen);
580 TRACE("writepos=%d, buf_mixpos=%d, primary_mixpos=%d, mixlen=%d\n", writepos, dsb->buf_mixpos, dsb->primary_mixpos, mixlen);
581 TRACE("looping=%d, leadin=%d, buflen=%d\n", dsb->playflags, dsb->leadin, dsb->tmp_buffer_len);
582
583 /* If leading in, only mix about 20 ms, and 'skip' mixing the rest, for more fluid pointer advancement */
584 if (dsb->leadin && dsb->state == STATE_STARTING)
585 {
586 if (mixlen > 2 * dsb->device->fraglen)
587 {
588 dsb->primary_mixpos += mixlen - 2 * dsb->device->fraglen;
589 dsb->primary_mixpos %= dsb->device->buflen;
590 }
591 }
592 dsb->leadin = FALSE;
593
594 /* calculate how much pre-buffering has already been done for this buffer */
595 primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
596
597 /* sanity */
598 if(mixlen < primary_done)
599 {
600 /* Should *NEVER* happen */
601 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);
602 return 0;
603 }
604
605 /* take into account already mixed data */
606 mixlen -= primary_done;
607
608 TRACE("primary_done=%d, mixlen (primary) = %i\n", primary_done, mixlen);
609
610 if (!mixlen)
611 return primary_done;
612
613 /* First try to mix to the end of the buffer if possible
614 * Theoretically it would allow for better optimization
615 */
616 if (mixlen + dsb->buf_mixpos >= dsb->tmp_buffer_len)
617 {
618 DWORD newmixed, mixfirst = dsb->tmp_buffer_len - dsb->buf_mixpos;
619 newmixed = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixfirst);
620 mixlen -= newmixed;
621
622 if (dsb->playflags & DSBPLAY_LOOPING)
623 while (newmixed && mixlen)
624 {
625 mixfirst = (dsb->tmp_buffer_len < mixlen ? dsb->tmp_buffer_len : mixlen);
626 newmixed = DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixfirst);
627 mixlen -= newmixed;
628 }
629 }
630 else DSOUND_MixInBuffer(dsb, dsb->primary_mixpos, mixlen);
631
632 /* re-calculate the primary done */
633 primary_done = DSOUND_BufPtrDiff(dsb->device->buflen, dsb->primary_mixpos, writepos);
634
635 TRACE("new primary_mixpos=%d, total mixed data=%d\n", dsb->primary_mixpos, primary_done);
636
637 /* Report back the total prebuffered amount for this buffer */
638 return primary_done;
639 }
640
641 /**
642 * For a DirectSoundDevice, go through all the currently playing buffers and
643 * mix them in to the device buffer.
644 *
645 * writepos = the current safe-to-write position in the primary buffer
646 * mixlen = the maximum amount to mix into the primary buffer
647 * (beyond the current writepos)
648 * mustlock = Do we have to fight for lock because we otherwise risk an underrun?
649 * recover = true if the sound device may have been reset and the write
650 * position in the device buffer changed
651 * all_stopped = reports back if all buffers have stopped
652 *
653 * Returns: the length beyond the writepos that was mixed to.
654 */
655
656 static DWORD DSOUND_MixToPrimary(const DirectSoundDevice *device, DWORD writepos, DWORD mixlen, BOOL mustlock, BOOL recover, BOOL *all_stopped)
657 {
658 INT i, len;
659 DWORD minlen = 0;
660 IDirectSoundBufferImpl *dsb;
661 BOOL gotall = TRUE;
662
663 /* unless we find a running buffer, all have stopped */
664 *all_stopped = TRUE;
665
666 TRACE("(%d,%d,%d)\n", writepos, mixlen, recover);
667 for (i = 0; i < device->nrofbuffers; i++) {
668 dsb = device->buffers[i];
669
670 TRACE("MixToPrimary for %p, state=%d\n", dsb, dsb->state);
671
672 if (dsb->buflen && dsb->state && !dsb->hwbuf) {
673 TRACE("Checking %p, mixlen=%d\n", dsb, mixlen);
674 if (!RtlAcquireResourceShared(&dsb->lock, mustlock))
675 {
676 gotall = FALSE;
677 continue;
678 }
679 /* if buffer is stopping it is stopped now */
680 if (dsb->state == STATE_STOPPING) {
681 dsb->state = STATE_STOPPED;
682 DSOUND_CheckEvent(dsb, 0, 0);
683 } else if (dsb->state != STATE_STOPPED) {
684
685 /* if recovering, reset the mix position */
686 if ((dsb->state == STATE_STARTING) || recover) {
687 dsb->primary_mixpos = writepos;
688 }
689
690 /* if the buffer was starting, it must be playing now */
691 if (dsb->state == STATE_STARTING)
692 dsb->state = STATE_PLAYING;
693
694 /* mix next buffer into the main buffer */
695 len = DSOUND_MixOne(dsb, writepos, mixlen);
696
697 if (!minlen) minlen = len;
698
699 /* record the minimum length mixed from all buffers */
700 /* we only want to return the length which *all* buffers have mixed */
701 else if (len) minlen = (len < minlen) ? len : minlen;
702
703 *all_stopped = FALSE;
704 }
705 RtlReleaseResource(&dsb->lock);
706 }
707 }
708
709 TRACE("Mixed at least %d from all buffers\n", minlen);
710 if (!gotall) return 0;
711 return minlen;
712 }
713
714 /**
715 * Add buffers to the emulated wave device system.
716 *
717 * device = The current dsound playback device
718 * force = If TRUE, the function will buffer up as many frags as possible,
719 * even though and will ignore the actual state of the primary buffer.
720 *
721 * Returns: None
722 */
723
724 static void DSOUND_WaveQueue(DirectSoundDevice *device, BOOL force)
725 {
726 DWORD prebuf_frags, wave_writepos, wave_fragpos, i;
727 TRACE("(%p)\n", device);
728
729 /* calculate the current wave frag position */
730 wave_fragpos = (device->pwplay + device->pwqueue) % device->helfrags;
731
732 /* calculate the current wave write position */
733 wave_writepos = wave_fragpos * device->fraglen;
734
735 TRACE("wave_fragpos = %i, wave_writepos = %i, pwqueue = %i, prebuf = %i\n",
736 wave_fragpos, wave_writepos, device->pwqueue, device->prebuf);
737
738 if (!force)
739 {
740 /* check remaining prebuffered frags */
741 prebuf_frags = device->mixpos / device->fraglen;
742 if (prebuf_frags == device->helfrags)
743 --prebuf_frags;
744 TRACE("wave_fragpos = %d, mixpos_frags = %d\n", wave_fragpos, prebuf_frags);
745 if (prebuf_frags < wave_fragpos)
746 prebuf_frags += device->helfrags;
747 prebuf_frags -= wave_fragpos;
748 TRACE("wanted prebuf_frags = %d\n", prebuf_frags);
749 }
750 else
751 /* buffer the maximum amount of frags */
752 prebuf_frags = device->prebuf;
753
754 /* limit to the queue we have left */
755 if ((prebuf_frags + device->pwqueue) > device->prebuf)
756 prebuf_frags = device->prebuf - device->pwqueue;
757
758 TRACE("prebuf_frags = %i\n", prebuf_frags);
759
760 /* adjust queue */
761 device->pwqueue += prebuf_frags;
762
763 /* get out of CS when calling the wave system */
764 LeaveCriticalSection(&(device->mixlock));
765 /* **** */
766
767 /* queue up the new buffers */
768 for(i=0; i<prebuf_frags; i++){
769 TRACE("queueing wave buffer %i\n", wave_fragpos);
770 waveOutWrite(device->hwo, &device->pwave[wave_fragpos], sizeof(WAVEHDR));
771 wave_fragpos++;
772 wave_fragpos %= device->helfrags;
773 }
774
775 /* **** */
776 EnterCriticalSection(&(device->mixlock));
777
778 TRACE("queue now = %i\n", device->pwqueue);
779 }
780
781 /**
782 * Perform mixing for a Direct Sound device. That is, go through all the
783 * secondary buffers (the sound bites currently playing) and mix them in
784 * to the primary buffer (the device buffer).
785 */
786 static void DSOUND_PerformMix(DirectSoundDevice *device)
787 {
788 TRACE("(%p)\n", device);
789
790 /* **** */
791 EnterCriticalSection(&(device->mixlock));
792
793 if (device->priolevel != DSSCL_WRITEPRIMARY) {
794 BOOL recover = FALSE, all_stopped = FALSE;
795 DWORD playpos, writepos, writelead, maxq, frag, prebuff_max, prebuff_left, size1, size2, mixplaypos, mixplaypos2;
796 LPVOID buf1, buf2;
797 BOOL lock = (device->hwbuf && !(device->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK));
798 BOOL mustlock = FALSE;
799 int nfiller;
800
801 /* the sound of silence */
802 nfiller = device->pwfx->wBitsPerSample == 8 ? 128 : 0;
803
804 /* get the position in the primary buffer */
805 if (DSOUND_PrimaryGetPosition(device, &playpos, &writepos) != 0){
806 LeaveCriticalSection(&(device->mixlock));
807 return;
808 }
809
810 TRACE("primary playpos=%d, writepos=%d, clrpos=%d, mixpos=%d, buflen=%d\n",
811 playpos,writepos,device->playpos,device->mixpos,device->buflen);
812 assert(device->playpos < device->buflen);
813
814 mixplaypos = DSOUND_bufpos_to_mixpos(device, device->playpos);
815 mixplaypos2 = DSOUND_bufpos_to_mixpos(device, playpos);
816
817 /* calc maximum prebuff */
818 prebuff_max = (device->prebuf * device->fraglen);
819 if (!device->hwbuf && playpos + prebuff_max >= device->helfrags * device->fraglen)
820 prebuff_max += device->buflen - device->helfrags * device->fraglen;
821
822 /* check how close we are to an underrun. It occurs when the writepos overtakes the mixpos */
823 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
824 writelead = DSOUND_BufPtrDiff(device->buflen, writepos, playpos);
825
826 /* check for underrun. underrun occurs when the write position passes the mix position
827 * also wipe out just-played sound data */
828 if((prebuff_left > prebuff_max) || (device->state == STATE_STOPPED) || (device->state == STATE_STARTING)){
829 if (device->state == STATE_STOPPING || device->state == STATE_PLAYING)
830 WARN("Probable buffer underrun\n");
831 else TRACE("Buffer starting or buffer underrun\n");
832
833 /* recover mixing for all buffers */
834 recover = TRUE;
835
836 /* reset mix position to write position */
837 device->mixpos = writepos;
838
839 ZeroMemory(device->mix_buffer, device->mix_buffer_len);
840 ZeroMemory(device->buffer, device->buflen);
841 } else if (playpos < device->playpos) {
842 buf1 = device->buffer + device->playpos;
843 buf2 = device->buffer;
844 size1 = device->buflen - device->playpos;
845 size2 = playpos;
846 FillMemory(device->mix_buffer + mixplaypos, device->mix_buffer_len - mixplaypos, 0);
847 FillMemory(device->mix_buffer, mixplaypos2, 0);
848 if (lock)
849 IDsDriverBuffer_Lock(device->hwbuf, &buf1, &size1, &buf2, &size2, device->playpos, size1+size2, 0);
850 FillMemory(buf1, size1, nfiller);
851 if (playpos && (!buf2 || !size2))
852 FIXME("%d: (%d, %d)=>(%d, %d) There should be an additional buffer here!!\n", __LINE__, device->playpos, device->mixpos, playpos, writepos);
853 FillMemory(buf2, size2, nfiller);
854 if (lock)
855 IDsDriverBuffer_Unlock(device->hwbuf, buf1, size1, buf2, size2);
856 } else {
857 buf1 = device->buffer + device->playpos;
858 buf2 = NULL;
859 size1 = playpos - device->playpos;
860 size2 = 0;
861 FillMemory(device->mix_buffer + mixplaypos, mixplaypos2 - mixplaypos, 0);
862 if (lock)
863 IDsDriverBuffer_Lock(device->hwbuf, &buf1, &size1, &buf2, &size2, device->playpos, size1+size2, 0);
864 FillMemory(buf1, size1, nfiller);
865 if (buf2 && size2)
866 {
867 FIXME("%d: There should be no additional buffer here!!\n", __LINE__);
868 FillMemory(buf2, size2, nfiller);
869 }
870 if (lock)
871 IDsDriverBuffer_Unlock(device->hwbuf, buf1, size1, buf2, size2);
872 }
873 device->playpos = playpos;
874
875 /* find the maximum we can prebuffer from current write position */
876 maxq = (writelead < prebuff_max) ? (prebuff_max - writelead) : 0;
877
878 TRACE("prebuff_left = %d, prebuff_max = %dx%d=%d, writelead=%d\n",
879 prebuff_left, device->prebuf, device->fraglen, prebuff_max, writelead);
880
881 /* Do we risk an 'underrun' if we don't advance pointer? */
882 if (writelead/device->fraglen <= ds_snd_queue_min || recover)
883 mustlock = TRUE;
884
885 if (lock)
886 IDsDriverBuffer_Lock(device->hwbuf, &buf1, &size1, &buf2, &size2, writepos, maxq, 0);
887
888 /* do the mixing */
889 frag = DSOUND_MixToPrimary(device, writepos, maxq, mustlock, recover, &all_stopped);
890
891 if (frag + writepos > device->buflen)
892 {
893 DWORD todo = device->buflen - writepos;
894 device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, todo);
895 device->normfunction(device->mix_buffer, device->buffer, frag - todo);
896 }
897 else
898 device->normfunction(device->mix_buffer + DSOUND_bufpos_to_mixpos(device, writepos), device->buffer + writepos, frag);
899
900 /* update the mix position, taking wrap-around into account */
901 device->mixpos = writepos + frag;
902 device->mixpos %= device->buflen;
903
904 if (lock)
905 {
906 DWORD frag2 = (frag > size1 ? frag - size1 : 0);
907 frag -= frag2;
908 if (frag2 > size2)
909 {
910 FIXME("Buffering too much! (%d, %d, %d, %d)\n", maxq, frag, size2, frag2 - size2);
911 frag2 = size2;
912 }
913 IDsDriverBuffer_Unlock(device->hwbuf, buf1, frag, buf2, frag2);
914 }
915
916 /* update prebuff left */
917 prebuff_left = DSOUND_BufPtrDiff(device->buflen, device->mixpos, playpos);
918
919 /* check if have a whole fragment */
920 if (prebuff_left >= device->fraglen){
921
922 /* update the wave queue if using wave system */
923 if (!device->hwbuf)
924 DSOUND_WaveQueue(device, FALSE);
925
926 /* buffers are full. start playing if applicable */
927 if(device->state == STATE_STARTING){
928 TRACE("started primary buffer\n");
929 if(DSOUND_PrimaryPlay(device) != DS_OK){
930 WARN("DSOUND_PrimaryPlay failed\n");
931 }
932 else{
933 /* we are playing now */
934 device->state = STATE_PLAYING;
935 }
936 }
937
938 /* buffers are full. start stopping if applicable */
939 if(device->state == STATE_STOPPED){
940 TRACE("restarting primary buffer\n");
941 if(DSOUND_PrimaryPlay(device) != DS_OK){
942 WARN("DSOUND_PrimaryPlay failed\n");
943 }
944 else{
945 /* start stopping again. as soon as there is no more data, it will stop */
946 device->state = STATE_STOPPING;
947 }
948 }
949 }
950
951 /* if device was stopping, its for sure stopped when all buffers have stopped */
952 else if((all_stopped == TRUE) && (device->state == STATE_STOPPING)){
953 TRACE("All buffers have stopped. Stopping primary buffer\n");
954 device->state = STATE_STOPPED;
955
956 /* stop the primary buffer now */
957 DSOUND_PrimaryStop(device);
958 }
959
960 } else {
961
962 /* update the wave queue if using wave system */
963 if (!device->hwbuf)
964 DSOUND_WaveQueue(device, TRUE);
965 else
966 /* Keep alsa happy, which needs GetPosition called once every 10 ms */
967 IDsDriverBuffer_GetPosition(device->hwbuf, NULL, NULL);
968
969 /* in the DSSCL_WRITEPRIMARY mode, the app is totally in charge... */
970 if (device->state == STATE_STARTING) {
971 if (DSOUND_PrimaryPlay(device) != DS_OK)
972 WARN("DSOUND_PrimaryPlay failed\n");
973 else
974 device->state = STATE_PLAYING;
975 }
976 else if (device->state == STATE_STOPPING) {
977 if (DSOUND_PrimaryStop(device) != DS_OK)
978 WARN("DSOUND_PrimaryStop failed\n");
979 else
980 device->state = STATE_STOPPED;
981 }
982 }
983
984 LeaveCriticalSection(&(device->mixlock));
985 /* **** */
986 }
987
988 void CALLBACK DSOUND_timer(UINT timerID, UINT msg, DWORD_PTR dwUser,
989 DWORD_PTR dw1, DWORD_PTR dw2)
990 {
991 DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
992 DWORD start_time = GetTickCount();
993 DWORD end_time;
994 TRACE("(%d,%d,0x%lx,0x%lx,0x%lx)\n",timerID,msg,dwUser,dw1,dw2);
995 TRACE("entering at %d\n", start_time);
996
997 if (DSOUND_renderer[device->drvdesc.dnDevNode] != device) {
998 ERR("dsound died without killing us?\n");
999 timeKillEvent(timerID);
1000 timeEndPeriod(DS_TIME_RES);
1001 return;
1002 }
1003
1004 RtlAcquireResourceShared(&(device->buffer_list_lock), TRUE);
1005
1006 if (device->ref)
1007 DSOUND_PerformMix(device);
1008
1009 RtlReleaseResource(&(device->buffer_list_lock));
1010
1011 end_time = GetTickCount();
1012 TRACE("completed processing at %d, duration = %d\n", end_time, end_time - start_time);
1013 }
1014
1015 void CALLBACK DSOUND_callback(HWAVEOUT hwo, UINT msg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1016 {
1017 DirectSoundDevice * device = (DirectSoundDevice*)dwUser;
1018 TRACE("(%p,%x,%lx,%lx,%lx)\n",hwo,msg,dwUser,dw1,dw2);
1019 TRACE("entering at %d, msg=%08x(%s)\n", GetTickCount(), msg,
1020 msg==MM_WOM_DONE ? "MM_WOM_DONE" : msg==MM_WOM_CLOSE ? "MM_WOM_CLOSE" :
1021 msg==MM_WOM_OPEN ? "MM_WOM_OPEN" : "UNKNOWN");
1022
1023 /* check if packet completed from wave driver */
1024 if (msg == MM_WOM_DONE) {
1025
1026 /* **** */
1027 EnterCriticalSection(&(device->mixlock));
1028
1029 TRACE("done playing primary pos=%d\n", device->pwplay * device->fraglen);
1030
1031 /* update playpos */
1032 device->pwplay++;
1033 device->pwplay %= device->helfrags;
1034
1035 /* sanity */
1036 if(device->pwqueue == 0){
1037 ERR("Wave queue corrupted!\n");
1038 }
1039
1040 /* update queue */
1041 device->pwqueue--;
1042
1043 LeaveCriticalSection(&(device->mixlock));
1044 /* **** */
1045 }
1046 TRACE("completed\n");
1047 }