Fixed some traces.
[wine] / dlls / dsound / primary.c
1 /*                      DirectSound
2  *
3  * Copyright 1998 Marcus Meissner
4  * Copyright 1998 Rob Riggs
5  * Copyright 2000-2002 TransGaming Technologies, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include <assert.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <sys/fcntl.h>
28 #ifdef HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif
31 #include <stdlib.h>
32 #include <string.h>
33 #include <math.h>       /* Insomnia - pow() function */
34
35 #include "windef.h"
36 #include "winbase.h"
37 #include "wingdi.h"
38 #include "winuser.h"
39 #include "winerror.h"
40 #include "mmsystem.h"
41 #include "winreg.h"
42 #include "winternl.h"
43 #include "mmddk.h"
44 #include "wine/windef16.h"
45 #include "wine/debug.h"
46 #include "dsound.h"
47 #include "dsdriver.h"
48 #include "dsound_private.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(dsound);
51
52 void DSOUND_RecalcPrimary(IDirectSoundImpl *This)
53 {
54         DWORD sw;
55         TRACE("(%p)\n",This);
56
57         sw = This->wfx.nChannels * (This->wfx.wBitsPerSample / 8);
58         if (This->hwbuf) {
59                 DWORD fraglen;
60                 /* let fragment size approximate the timer delay */
61                 fraglen = (This->wfx.nSamplesPerSec * DS_TIME_DEL / 1000) * sw;
62                 /* reduce fragment size until an integer number of them fits in the buffer */
63                 /* (FIXME: this may or may not be a good idea) */
64                 while (This->buflen % fraglen) fraglen -= sw;
65                 This->fraglen = fraglen;
66                 TRACE("fraglen=%ld\n", This->fraglen);
67         }
68         /* calculate the 10ms write lead */
69         This->writelead = (This->wfx.nSamplesPerSec / 100) * sw;
70 }
71
72 static HRESULT DSOUND_PrimaryOpen(IDirectSoundImpl *This)
73 {
74         HRESULT err = DS_OK;
75         TRACE("(%p)\n",This);
76
77         DSOUND_RecalcVolPan(&(This->volpan));
78
79         /* are we using waveOut stuff? */
80         if (!This->hwbuf) {
81                 LPBYTE newbuf;
82                 DWORD buflen;
83                 HRESULT merr = DS_OK;
84                 /* Start in pause mode, to allow buffers to get filled */
85                 waveOutPause(This->hwo);
86                 if (This->state == STATE_PLAYING) This->state = STATE_STARTING;
87                 else if (This->state == STATE_STOPPING) This->state = STATE_STOPPED;
88                 /* use fragments of 10ms (1/100s) each (which should get us within
89                  * the documented write cursor lead of 10-15ms) */
90                 buflen = ((This->wfx.nAvgBytesPerSec / 100) & ~3) * DS_HEL_FRAGS;
91                 TRACE("desired buflen=%ld, old buffer=%p\n", buflen, This->buffer);
92                 /* reallocate emulated primary buffer */
93                 newbuf = (LPBYTE)HeapReAlloc(GetProcessHeap(),0,This->buffer,buflen);
94                 if (newbuf == NULL) {
95                         ERR("failed to allocate primary buffer\n");
96                         merr = DSERR_OUTOFMEMORY;
97                         /* but the old buffer might still exist and must be re-prepared */
98                 } else {
99                         This->buffer = newbuf;
100                         This->buflen = buflen;
101                 }
102                 if (This->buffer) {
103                         unsigned c;
104
105                         This->fraglen = This->buflen / DS_HEL_FRAGS;
106
107                         /* prepare fragment headers */
108                         for (c=0; c<DS_HEL_FRAGS; c++) {
109                                 This->pwave[c]->lpData = This->buffer + c*This->fraglen;
110                                 This->pwave[c]->dwBufferLength = This->fraglen;
111                                 This->pwave[c]->dwUser = (DWORD)This;
112                                 This->pwave[c]->dwFlags = 0;
113                                 This->pwave[c]->dwLoops = 0;
114                                 err = mmErr(waveOutPrepareHeader(This->hwo,This->pwave[c],sizeof(WAVEHDR)));
115                                 if (err != DS_OK) {
116                                         while (c--)
117                                                 waveOutUnprepareHeader(This->hwo,This->pwave[c],sizeof(WAVEHDR));
118                                         break;
119                                 }
120                         }
121
122                         This->pwplay = 0;
123                         This->pwwrite = 0;
124                         This->pwqueue = 0;
125                         This->playpos = 0;
126                         This->mixpos = 0;
127                         memset(This->buffer, (This->wfx.wBitsPerSample == 16) ? 0 : 128, This->buflen);
128                         TRACE("fraglen=%ld\n", This->fraglen);
129                         DSOUND_WaveQueue(This, (DWORD)-1);
130                 }
131                 if ((err == DS_OK) && (merr != DS_OK))
132                         err = merr;
133
134                 if (!err) {
135                         DWORD vol = (This->volpan.dwTotalLeftAmpFactor & 0xffff) | (This->volpan.dwTotalRightAmpFactor << 16);
136                         err = mmErr(waveOutSetVolume(This->hwo, vol));
137                 }
138         } else {
139                 err = IDsDriverBuffer_SetVolumePan(This->hwbuf, &(This->volpan));
140         }
141
142         return err;
143 }
144
145
146 static void DSOUND_PrimaryClose(IDirectSoundImpl *This)
147 {
148         TRACE("(%p)\n",This);
149
150         /* are we using waveOut stuff? */
151         if (!This->hwbuf) {
152                 unsigned c;
153
154                 This->pwqueue = (DWORD)-1; /* resetting queues */
155                 waveOutReset(This->hwo);
156                 for (c=0; c<DS_HEL_FRAGS; c++)
157                         waveOutUnprepareHeader(This->hwo, This->pwave[c], sizeof(WAVEHDR));
158                 This->pwqueue = 0;
159         }
160 }
161
162 HRESULT DSOUND_PrimaryCreate(IDirectSoundImpl *This)
163 {
164         HRESULT err = DS_OK;
165         TRACE("(%p)\n",This);
166
167         This->buflen = This->wfx.nAvgBytesPerSec;
168
169         /* FIXME: verify that hardware capabilities (DSCAPS_PRIMARY flags) match */
170
171         if (This->driver) {
172                 err = IDsDriver_CreateSoundBuffer(This->driver,&(This->wfx),
173                                                   DSBCAPS_PRIMARYBUFFER,0,
174                                                   &(This->buflen),&(This->buffer),
175                                                   (LPVOID*)&(This->hwbuf));
176                 if (err != DS_OK) {
177                         WARN("IDsDriver_CreateSoundBuffer failed\n");
178                         return err;
179                 }
180         }
181         if (!This->hwbuf) {
182                 /* Allocate memory for HEL buffer headers */
183                 unsigned c;
184                 for (c=0; c<DS_HEL_FRAGS; c++) {
185                         This->pwave[c] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(WAVEHDR));
186                         if (!This->pwave[c]) {
187                                 /* Argh, out of memory */
188                                 while (c--) {
189                                         HeapFree(GetProcessHeap(),0,This->pwave[c]);
190                                 }
191                                 WARN("out of memory\n");
192                                 return DSERR_OUTOFMEMORY;
193                         }
194                 }
195         }
196
197         err = DSOUND_PrimaryOpen(This);
198
199         if (err != DS_OK) {
200                 WARN("DSOUND_PrimaryOpen failed\n");
201                 return err;
202         }
203
204         /* calculate fragment size and write lead */
205         DSOUND_RecalcPrimary(This);
206         This->state = STATE_STOPPED;
207         return DS_OK;
208 }
209
210 HRESULT DSOUND_PrimaryDestroy(IDirectSoundImpl *This)
211 {
212         TRACE("(%p)\n",This);
213
214         DSOUND_PrimaryClose(This);
215         if (This->hwbuf) {
216                 if (IDsDriverBuffer_Release(This->hwbuf) == 0)
217                         This->hwbuf = 0;
218         } else {
219                 unsigned c;
220                 for (c=0; c<DS_HEL_FRAGS; c++) {
221                         HeapFree(GetProcessHeap(),0,This->pwave[c]);
222                 }
223         }
224         return DS_OK;
225 }
226
227 HRESULT DSOUND_PrimaryPlay(IDirectSoundImpl *This)
228 {
229         HRESULT err = DS_OK;
230         TRACE("(%p)\n",This);
231
232         if (This->hwbuf) {
233                 err = IDsDriverBuffer_Play(This->hwbuf, 0, 0, DSBPLAY_LOOPING);
234                 if (err != DS_OK)
235                         WARN("IDsDriverBuffer_Play failed\n");
236         } else {
237                 err = mmErr(waveOutRestart(This->hwo));
238                 if (err != DS_OK)
239                         WARN("waveOutRestart failed\n");
240         }
241
242         return err;
243 }
244
245 HRESULT DSOUND_PrimaryStop(IDirectSoundImpl *This)
246 {
247         HRESULT err = DS_OK;
248         TRACE("(%p)\n",This);
249
250         if (This->hwbuf) {
251                 err = IDsDriverBuffer_Stop(This->hwbuf);
252                 if (err == DSERR_BUFFERLOST) {
253                         DWORD flags = CALLBACK_FUNCTION;
254                         if (ds_hw_accel != DS_HW_ACCEL_EMULATION)
255                                 flags |= WAVE_DIRECTSOUND;
256                         /* Wine-only: the driver wants us to reopen the device */
257                         /* FIXME: check for errors */
258                         IDsDriverBuffer_Release(This->hwbuf);
259                         waveOutClose(This->hwo);
260                         This->hwo = 0;
261                         err = mmErr(waveOutOpen(&(This->hwo), This->drvdesc.dnDevNode,
262                                                 &(This->wfx), (DWORD)DSOUND_callback, (DWORD)This,
263                                                 flags));
264                         if (err == DS_OK) {
265                                 err = IDsDriver_CreateSoundBuffer(This->driver,&(This->wfx),
266                                                                   DSBCAPS_PRIMARYBUFFER,0,
267                                                                   &(This->buflen),&(This->buffer),
268                                                                   (LPVOID)&(This->hwbuf));
269                                 if (err != DS_OK)
270                                         WARN("IDsDriver_CreateSoundBuffer failed\n");
271                         } else {
272                                 WARN("waveOutOpen failed\n");
273                         }
274                 } else if (err != DS_OK) {
275                         WARN("IDsDriverBuffer_Stop failed\n");
276                 }
277         } else {
278                 err = mmErr(waveOutPause(This->hwo));
279                 if (err != DS_OK)
280                         WARN("waveOutPause failed\n");
281         }
282         return err;
283 }
284
285 HRESULT DSOUND_PrimaryGetPosition(IDirectSoundImpl *This, LPDWORD playpos, LPDWORD writepos)
286 {
287         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
288
289         if (This->hwbuf) {
290                 HRESULT err=IDsDriverBuffer_GetPosition(This->hwbuf,playpos,writepos);
291                 if (err) {
292                         WARN("IDsDriverBuffer_GetPosition failed\n");
293                         return err;
294                 }
295         }
296         else {
297                 if (playpos) {
298                         MMTIME mtime;
299                         mtime.wType = TIME_BYTES;
300                         waveOutGetPosition(This->hwo, &mtime, sizeof(mtime));
301                         mtime.u.cb = mtime.u.cb % This->buflen;
302                         *playpos = mtime.u.cb;
303                 }
304                 if (writepos) {
305                         /* the writepos should only be used by apps with WRITEPRIMARY priority,
306                          * in which case our software mixer is disabled anyway */
307                         *writepos = (This->pwplay + ds_hel_margin) * This->fraglen;
308                         while (*writepos >= This->buflen)
309                                 *writepos -= This->buflen;
310                 }
311         }
312         TRACE("playpos = %ld, writepos = %ld (%p, time=%ld)\n", playpos?*playpos:0, writepos?*writepos:0, This, GetTickCount());
313         return DS_OK;
314 }
315
316
317 /*******************************************************************************
318  *              PrimaryBuffer
319  */
320 /* This sets this format for the <em>Primary Buffer Only</em> */
321 /* See file:///cdrom/sdk52/docs/worddoc/dsound.doc page 120 */
322 static HRESULT WINAPI PrimaryBufferImpl_SetFormat(
323         LPDIRECTSOUNDBUFFER8 iface,LPWAVEFORMATEX wfex
324 ) {
325         ICOM_THIS(PrimaryBufferImpl,iface);
326         IDirectSoundImpl* dsound = This->dsound;
327         IDirectSoundBufferImpl** dsb;
328         HRESULT err = DS_OK;
329         int                     i;
330         TRACE("(%p,%p)\n",This,wfex);
331
332         if (This->dsound->priolevel == DSSCL_NORMAL) {
333                 WARN("failed priority check!\n");
334                 return DSERR_PRIOLEVELNEEDED;
335         }
336
337         /* Let's be pedantic! */
338         if (wfex == NULL) {
339                 WARN("invalid parameter: wfex==NULL!\n");
340                 return DSERR_INVALIDPARAM;
341         }
342         TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld,"
343               "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
344               wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
345               wfex->nAvgBytesPerSec, wfex->nBlockAlign,
346               wfex->wBitsPerSample, wfex->cbSize);
347
348         if ((wfex->wFormatTag != WAVE_FORMAT_PCM) ||
349             (wfex->nChannels < 1) || (wfex->nChannels > 2) ||
350             (wfex->nSamplesPerSec < 1) ||
351             ((wfex->wBitsPerSample != 8) && (wfex->wBitsPerSample != 16))) {
352                 WARN("invalid paramemer: unsupported format!\n");
353                 return DSERR_INVALIDPARAM;
354         }
355
356         /* **** */
357         RtlAcquireResourceExclusive(&(dsound->lock), TRUE);
358
359         if (dsound->wfx.nSamplesPerSec != wfex->nSamplesPerSec) {
360                 dsb = dsound->buffers;
361                 for (i = 0; i < dsound->nrofbuffers; i++, dsb++) {
362                         /* **** */
363                         EnterCriticalSection(&((*dsb)->lock));
364
365                         (*dsb)->freqAdjust = ((*dsb)->freq << DSOUND_FREQSHIFT) /
366                                 wfex->nSamplesPerSec;
367
368                         LeaveCriticalSection(&((*dsb)->lock));
369                         /* **** */
370                 }
371         }
372
373         dsound->wfx.nSamplesPerSec = wfex->nSamplesPerSec;
374         dsound->wfx.nChannels = wfex->nChannels;
375         dsound->wfx.wBitsPerSample = wfex->wBitsPerSample;
376         dsound->wfx.nBlockAlign = dsound->wfx.wBitsPerSample / 8 * dsound->wfx.nChannels;
377         dsound->wfx.nAvgBytesPerSec =
378                 dsound->wfx.nSamplesPerSec * dsound->wfx.nBlockAlign;
379
380         if (dsound->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMSETFORMAT) {
381                 DWORD flags = CALLBACK_FUNCTION;
382                 if (ds_hw_accel != DS_HW_ACCEL_EMULATION)
383                         flags |= WAVE_DIRECTSOUND;
384                 /* FIXME: check for errors */
385                 DSOUND_PrimaryClose(dsound);
386                 waveOutClose(dsound->hwo);
387                 dsound->hwo = 0;
388                 err = mmErr(waveOutOpen(&(dsound->hwo), dsound->drvdesc.dnDevNode,
389                                         &(dsound->wfx), (DWORD)DSOUND_callback, (DWORD)dsound,
390                                         flags));
391                 if (err == DS_OK) {
392                     err = DSOUND_PrimaryOpen(dsound);
393                     if (err != DS_OK) {
394                             WARN("DSOUND_PrimaryOpen failed\n");
395                             RtlReleaseResource(&(dsound->lock));
396                             return err;
397                     }
398                 } else {
399                         WARN("waveOutOpen failed\n");
400                         RtlReleaseResource(&(dsound->lock));
401                         return err;
402                 }
403         }
404         if (dsound->hwbuf) {
405                 err = IDsDriverBuffer_SetFormat(dsound->hwbuf, &(dsound->wfx));
406                 if (err == DSERR_BUFFERLOST) {
407                         /* Wine-only: the driver wants us to recreate the HW buffer */
408                         IDsDriverBuffer_Release(dsound->hwbuf);
409                         err = IDsDriver_CreateSoundBuffer(dsound->driver,&(dsound->wfx),
410                                                           DSBCAPS_PRIMARYBUFFER,0,
411                                                           &(dsound->buflen),&(dsound->buffer),
412                                                           (LPVOID)&(dsound->hwbuf));
413                         if (err != DS_OK) {
414                                 WARN("IDsDriver_CreateSoundBuffer failed\n");
415                                 RtlReleaseResource(&(dsound->lock));
416                                 return err;
417                         }
418                         if (dsound->state == STATE_PLAYING) dsound->state = STATE_STARTING;
419                         else if (dsound->state == STATE_STOPPING) dsound->state = STATE_STOPPED;
420                 } else {
421                         WARN("IDsDriverBuffer_SetFormat failed\n");
422                         RtlReleaseResource(&(dsound->lock));
423                         return err;
424                 }
425                 /* FIXME: should we set err back to DS_OK in all cases ? */
426         }
427         DSOUND_RecalcPrimary(dsound);
428
429         RtlReleaseResource(&(dsound->lock));
430         /* **** */
431
432         return err;
433 }
434
435 static HRESULT WINAPI PrimaryBufferImpl_SetVolume(
436         LPDIRECTSOUNDBUFFER8 iface,LONG vol
437 ) {
438         ICOM_THIS(PrimaryBufferImpl,iface);
439         IDirectSoundImpl* dsound = This->dsound;
440         LONG oldVol;
441
442         TRACE("(%p,%ld)\n",This,vol);
443
444         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
445                 WARN("control unavailable\n");
446                 return DSERR_CONTROLUNAVAIL;
447         }
448
449         if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN)) {
450                 WARN("invalid parameter: vol = %ld\n", vol);
451                 return DSERR_INVALIDPARAM;
452         }
453
454         /* **** */
455         EnterCriticalSection(&(dsound->mixlock));
456
457         oldVol = dsound->volpan.lVolume;
458         dsound->volpan.lVolume = vol;
459         DSOUND_RecalcVolPan(&dsound->volpan);
460
461         if (vol != oldVol) {
462                 if (dsound->hwbuf) {
463                         HRESULT hres;
464                         hres = IDsDriverBuffer_SetVolumePan(dsound->hwbuf, &(dsound->volpan));
465                         if (hres != DS_OK) {
466                                 LeaveCriticalSection(&(dsound->mixlock));
467                                 WARN("IDsDriverBuffer_SetVolumePan failed\n");
468                                 return hres;
469                         }
470                 } else {
471                         DWORD vol = (dsound->volpan.dwTotalLeftAmpFactor & 0xffff) | (dsound->volpan.dwTotalRightAmpFactor << 16);
472                         waveOutSetVolume(dsound->hwo, vol);
473                 }
474         }
475
476         LeaveCriticalSection(&(dsound->mixlock));
477         /* **** */
478
479         return DS_OK;
480 }
481
482 static HRESULT WINAPI PrimaryBufferImpl_GetVolume(
483         LPDIRECTSOUNDBUFFER8 iface,LPLONG vol
484 ) {
485         ICOM_THIS(PrimaryBufferImpl,iface);
486         TRACE("(%p,%p)\n",This,vol);
487
488         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
489                 WARN("control unavailable\n");
490                 return DSERR_CONTROLUNAVAIL;
491         }
492
493         if (vol == NULL) {
494                 WARN("invalid parameter: vol = NULL\n");
495                 return DSERR_INVALIDPARAM;
496         }
497
498         *vol = This->dsound->volpan.lVolume;
499         return DS_OK;
500 }
501
502 static HRESULT WINAPI PrimaryBufferImpl_SetFrequency(
503         LPDIRECTSOUNDBUFFER8 iface,DWORD freq
504 ) {
505         ICOM_THIS(PrimaryBufferImpl,iface);
506
507         TRACE("(%p,%ld)\n",This,freq);
508
509         /* You cannot set the frequency of the primary buffer */
510         WARN("control unavailable\n");
511         return DSERR_CONTROLUNAVAIL;
512 }
513
514 static HRESULT WINAPI PrimaryBufferImpl_Play(
515         LPDIRECTSOUNDBUFFER8 iface,DWORD reserved1,DWORD reserved2,DWORD flags
516 ) {
517         ICOM_THIS(PrimaryBufferImpl,iface);
518         IDirectSoundImpl* dsound = This->dsound;
519
520         TRACE("(%p,%08lx,%08lx,%08lx)\n",
521                 This,reserved1,reserved2,flags
522         );
523
524         if (!(flags & DSBPLAY_LOOPING)) {
525                 WARN("invalid parameter: flags = %08lx\n", flags);
526                 return DSERR_INVALIDPARAM;
527         }
528
529         /* **** */
530         EnterCriticalSection(&(dsound->mixlock));
531
532         if (dsound->state == STATE_STOPPED)
533                 dsound->state = STATE_STARTING;
534         else if (dsound->state == STATE_STOPPING)
535                 dsound->state = STATE_PLAYING;
536
537         LeaveCriticalSection(&(dsound->mixlock));
538         /* **** */
539
540         return DS_OK;
541 }
542
543 static HRESULT WINAPI PrimaryBufferImpl_Stop(LPDIRECTSOUNDBUFFER8 iface)
544 {
545         ICOM_THIS(PrimaryBufferImpl,iface);
546         IDirectSoundImpl* dsound = This->dsound;
547
548         TRACE("(%p)\n",This);
549
550         /* **** */
551         EnterCriticalSection(&(dsound->mixlock));
552
553         if (dsound->state == STATE_PLAYING)
554                 dsound->state = STATE_STOPPING;
555         else if (dsound->state == STATE_STARTING)
556                 dsound->state = STATE_STOPPED;
557
558         LeaveCriticalSection(&(dsound->mixlock));
559         /* **** */
560
561         return DS_OK;
562 }
563
564 static DWORD WINAPI PrimaryBufferImpl_AddRef(LPDIRECTSOUNDBUFFER8 iface) {
565         ICOM_THIS(PrimaryBufferImpl,iface);
566         DWORD ref;
567
568         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
569         ref = InterlockedIncrement(&(This->ref));
570
571         return ref;
572 }
573
574 static DWORD WINAPI PrimaryBufferImpl_Release(LPDIRECTSOUNDBUFFER8 iface) {
575         ICOM_THIS(PrimaryBufferImpl,iface);
576         DWORD ref;
577
578         TRACE("(%p) ref was %ld, thread is %04lx\n",This, This->ref, GetCurrentThreadId());
579         ref = InterlockedDecrement(&(This->ref));
580
581         if (ref == 0) {
582                 This->dsound->primary = NULL;
583                 IDirectSound_Release((LPDIRECTSOUND)This->dsound);
584                 HeapFree(GetProcessHeap(),0,This);
585                 TRACE("(%p) released\n",This);
586         }
587
588         return ref;
589 }
590
591 static HRESULT WINAPI PrimaryBufferImpl_GetCurrentPosition(
592         LPDIRECTSOUNDBUFFER8 iface,LPDWORD playpos,LPDWORD writepos
593 ) {
594         HRESULT hres;
595         ICOM_THIS(PrimaryBufferImpl,iface);
596         IDirectSoundImpl* dsound = This->dsound;
597
598         TRACE("(%p,%p,%p)\n",This,playpos,writepos);
599         hres = DSOUND_PrimaryGetPosition(dsound, playpos, writepos);
600         if (hres != DS_OK) {
601                 WARN("DSOUND_PrimaryGetPosition failed\n");
602                 return hres;
603         }
604         if (writepos) {
605                 if (dsound->state != STATE_STOPPED)
606                         /* apply the documented 10ms lead to writepos */
607                         *writepos += dsound->writelead;
608                 while (*writepos >= dsound->buflen) *writepos -= dsound->buflen;
609         }
610         TRACE("playpos = %ld, writepos = %ld (%p, time=%ld)\n", playpos?*playpos:0, writepos?*writepos:0, This, GetTickCount());
611         return DS_OK;
612 }
613
614 static HRESULT WINAPI PrimaryBufferImpl_GetStatus(
615         LPDIRECTSOUNDBUFFER8 iface,LPDWORD status
616 ) {
617         ICOM_THIS(PrimaryBufferImpl,iface);
618         TRACE("(%p,%p), thread is %04lx\n",This,status,GetCurrentThreadId());
619
620         if (status == NULL) {
621                 WARN("invalid parameter: status == NULL\n");
622                 return DSERR_INVALIDPARAM;
623         }
624
625         *status = 0;
626         if ((This->dsound->state == STATE_STARTING) ||
627             (This->dsound->state == STATE_PLAYING))
628                 *status |= DSBSTATUS_PLAYING | DSBSTATUS_LOOPING;
629
630         TRACE("status=%lx\n", *status);
631         return DS_OK;
632 }
633
634
635 static HRESULT WINAPI PrimaryBufferImpl_GetFormat(
636         LPDIRECTSOUNDBUFFER8 iface,LPWAVEFORMATEX lpwf,DWORD wfsize,LPDWORD wfwritten
637 ) {
638         ICOM_THIS(PrimaryBufferImpl,iface);
639         TRACE("(%p,%p,%ld,%p)\n",This,lpwf,wfsize,wfwritten);
640
641         if (wfsize>sizeof(This->dsound->wfx))
642                 wfsize = sizeof(This->dsound->wfx);
643         if (lpwf) {     /* NULL is valid */
644                 memcpy(lpwf,&(This->dsound->wfx),wfsize);
645                 if (wfwritten)
646                         *wfwritten = wfsize;
647         } else {
648                 if (wfwritten)
649                         *wfwritten = sizeof(This->dsound->wfx);
650                 else {
651                         WARN("invalid parameter: wfwritten == NULL\n");
652                         return DSERR_INVALIDPARAM;
653                 }
654         }
655
656         return DS_OK;
657 }
658
659 static HRESULT WINAPI PrimaryBufferImpl_Lock(
660         LPDIRECTSOUNDBUFFER8 iface,DWORD writecursor,DWORD writebytes,LPVOID lplpaudioptr1,LPDWORD audiobytes1,LPVOID lplpaudioptr2,LPDWORD audiobytes2,DWORD flags
661 ) {
662         ICOM_THIS(PrimaryBufferImpl,iface);
663         IDirectSoundImpl* dsound = This->dsound;
664
665         TRACE("(%p,%ld,%ld,%p,%p,%p,%p,0x%08lx) at %ld\n",
666                 This,
667                 writecursor,
668                 writebytes,
669                 lplpaudioptr1,
670                 audiobytes1,
671                 lplpaudioptr2,
672                 audiobytes2,
673                 flags,
674                 GetTickCount()
675         );
676
677         if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
678                 WARN("failed priority check!\n");
679                 return DSERR_PRIOLEVELNEEDED;
680         }
681
682         if (flags & DSBLOCK_FROMWRITECURSOR) {
683                 DWORD writepos;
684                 HRESULT hres;
685                 /* GetCurrentPosition does too much magic to duplicate here */
686                 hres = IDirectSoundBuffer_GetCurrentPosition(iface, NULL, &writepos);
687                 if (hres != DS_OK) {
688                         WARN("IDirectSoundBuffer_GetCurrentPosition failed\n");
689                         return hres;
690                 }
691                 writecursor += writepos;
692         }
693         while (writecursor >= dsound->buflen)
694                 writecursor -= dsound->buflen;
695         if (flags & DSBLOCK_ENTIREBUFFER)
696                 writebytes = dsound->buflen;
697         if (writebytes > dsound->buflen)
698                 writebytes = dsound->buflen;
699
700         assert(audiobytes1!=audiobytes2);
701         assert(lplpaudioptr1!=lplpaudioptr2);
702
703         if (!(dsound->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK) && dsound->hwbuf) {
704                 HRESULT hres;
705                 hres = IDsDriverBuffer_Lock(dsound->hwbuf,
706                                             lplpaudioptr1, audiobytes1,
707                                             lplpaudioptr2, audiobytes2,
708                                             writecursor, writebytes,
709                                             0);
710                 if (hres != DS_OK) {
711                         WARN("IDsDriverBuffer_Lock failed\n");
712                         return hres;
713                 }
714         } else {
715                 if (writecursor+writebytes <= dsound->buflen) {
716                         *(LPBYTE*)lplpaudioptr1 = dsound->buffer+writecursor;
717                         *audiobytes1 = writebytes;
718                         if (lplpaudioptr2)
719                                 *(LPBYTE*)lplpaudioptr2 = NULL;
720                         if (audiobytes2)
721                                 *audiobytes2 = 0;
722                         TRACE("->%ld.0\n",writebytes);
723                 } else {
724                         *(LPBYTE*)lplpaudioptr1 = dsound->buffer+writecursor;
725                         *audiobytes1 = dsound->buflen-writecursor;
726                         if (lplpaudioptr2)
727                                 *(LPBYTE*)lplpaudioptr2 = dsound->buffer;
728                         if (audiobytes2)
729                                 *audiobytes2 = writebytes-(dsound->buflen-writecursor);
730                         TRACE("->%ld.%ld\n",*audiobytes1,audiobytes2?*audiobytes2:0);
731                 }
732         }
733         return DS_OK;
734 }
735
736 static HRESULT WINAPI PrimaryBufferImpl_SetCurrentPosition(
737         LPDIRECTSOUNDBUFFER8 iface,DWORD newpos
738 ) {
739         ICOM_THIS(PrimaryBufferImpl,iface);
740         TRACE("(%p,%ld)\n",This,newpos);
741
742         /* You cannot set the position of the primary buffer */
743         WARN("invalid call\n");
744         return DSERR_INVALIDCALL;
745 }
746
747 static HRESULT WINAPI PrimaryBufferImpl_SetPan(
748         LPDIRECTSOUNDBUFFER8 iface,LONG pan
749 ) {
750         ICOM_THIS(PrimaryBufferImpl,iface);
751         IDirectSoundImpl* dsound = This->dsound;
752         LONG oldPan;
753
754         TRACE("(%p,%ld)\n",This,pan);
755
756         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
757                 WARN("control unavailable\n");
758                 return DSERR_CONTROLUNAVAIL;
759         }
760
761         if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT)) {
762                 WARN("invalid parameter: pan = %ld\n", pan);
763                 return DSERR_INVALIDPARAM;
764         }
765
766         /* **** */
767         EnterCriticalSection(&(dsound->mixlock));
768
769         oldPan = dsound->volpan.lPan;
770         dsound->volpan.lPan = pan;
771         DSOUND_RecalcVolPan(&dsound->volpan);
772
773         if (pan != oldPan) {
774                 if (dsound->hwbuf) {
775                         HRESULT hres;
776                         hres = IDsDriverBuffer_SetVolumePan(dsound->hwbuf, &(dsound->volpan));
777                         if (hres != DS_OK) {
778                                 LeaveCriticalSection(&(dsound->mixlock));
779                                 WARN("IDsDriverBuffer_SetVolumePan failed\n");
780                                 return hres;
781                         }
782                 }
783                 else {
784                         DWORD vol = (dsound->volpan.dwTotalLeftAmpFactor & 0xffff) | (dsound->volpan.dwTotalRightAmpFactor << 16);
785                         waveOutSetVolume(dsound->hwo, vol);
786                 }
787         }
788
789         LeaveCriticalSection(&(dsound->mixlock));
790         /* **** */
791
792         return DS_OK;
793 }
794
795 static HRESULT WINAPI PrimaryBufferImpl_GetPan(
796         LPDIRECTSOUNDBUFFER8 iface,LPLONG pan
797 ) {
798         ICOM_THIS(PrimaryBufferImpl,iface);
799         TRACE("(%p,%p)\n",This,pan);
800
801         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
802                 WARN("control unavailable\n");
803                 return DSERR_CONTROLUNAVAIL;
804         }
805
806         if (pan == NULL) {
807                 WARN("invalid parameter: pan == NULL\n");
808                 return DSERR_INVALIDPARAM;
809         }
810
811         *pan = This->dsound->volpan.lPan;
812
813         return DS_OK;
814 }
815
816 static HRESULT WINAPI PrimaryBufferImpl_Unlock(
817         LPDIRECTSOUNDBUFFER8 iface,LPVOID p1,DWORD x1,LPVOID p2,DWORD x2
818 ) {
819         ICOM_THIS(PrimaryBufferImpl,iface);
820         IDirectSoundImpl* dsound = This->dsound;
821
822         TRACE("(%p,%p,%ld,%p,%ld)\n", This,p1,x1,p2,x2);
823
824         if (dsound->priolevel != DSSCL_WRITEPRIMARY) {
825                 WARN("failed priority check!\n");
826                 return DSERR_PRIOLEVELNEEDED;
827         }
828
829         if (!(dsound->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK) && dsound->hwbuf) {
830                 HRESULT hres;
831                 
832                 hres = IDsDriverBuffer_Unlock(dsound->hwbuf, p1, x1, p2, x2);
833                 if (hres != DS_OK) {
834                         WARN("IDsDriverBuffer_Unlock failed\n");
835                         return hres;
836                 }
837         }
838
839         return DS_OK;
840 }
841
842 static HRESULT WINAPI PrimaryBufferImpl_Restore(
843         LPDIRECTSOUNDBUFFER8 iface
844 ) {
845         ICOM_THIS(PrimaryBufferImpl,iface);
846         FIXME("(%p):stub\n",This);
847         return DS_OK;
848 }
849
850 static HRESULT WINAPI PrimaryBufferImpl_GetFrequency(
851         LPDIRECTSOUNDBUFFER8 iface,LPDWORD freq
852 ) {
853         ICOM_THIS(PrimaryBufferImpl,iface);
854         TRACE("(%p,%p)\n",This,freq);
855
856         if (freq == NULL) {
857                 WARN("invalid parameter: freq == NULL\n");
858                 return DSERR_INVALIDPARAM;
859         }
860
861         if (!(This->dsound->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) {
862                 WARN("control unavailable\n");
863                 return DSERR_CONTROLUNAVAIL;
864         }
865
866         *freq = This->dsound->wfx.nSamplesPerSec;
867         TRACE("-> %ld\n", *freq);
868
869         return DS_OK;
870 }
871
872 static HRESULT WINAPI PrimaryBufferImpl_SetFX(
873         LPDIRECTSOUNDBUFFER8 iface,DWORD dwEffectsCount,LPDSEFFECTDESC pDSFXDesc,LPDWORD pdwResultCodes
874 ) {
875         ICOM_THIS(PrimaryBufferImpl,iface);
876         DWORD u;
877
878         FIXME("(%p,%lu,%p,%p): stub\n",This,dwEffectsCount,pDSFXDesc,pdwResultCodes);
879
880         if (pdwResultCodes)
881                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
882
883         WARN("control unavailable\n");
884         return DSERR_CONTROLUNAVAIL;
885 }
886
887 static HRESULT WINAPI PrimaryBufferImpl_AcquireResources(
888         LPDIRECTSOUNDBUFFER8 iface,DWORD dwFlags,DWORD dwEffectsCount,LPDWORD pdwResultCodes
889 ) {
890         ICOM_THIS(PrimaryBufferImpl,iface);
891         DWORD u;
892
893         FIXME("(%p,%08lu,%lu,%p): stub\n",This,dwFlags,dwEffectsCount,pdwResultCodes);
894
895         if (pdwResultCodes)
896                 for (u=0; u<dwEffectsCount; u++) pdwResultCodes[u] = DSFXR_UNKNOWN;
897
898         WARN("control unavailable\n");
899         return DSERR_CONTROLUNAVAIL;
900 }
901
902 static HRESULT WINAPI PrimaryBufferImpl_GetObjectInPath(
903         LPDIRECTSOUNDBUFFER8 iface,REFGUID rguidObject,DWORD dwIndex,REFGUID rguidInterface,LPVOID* ppObject
904 ) {
905         ICOM_THIS(PrimaryBufferImpl,iface);
906
907         FIXME("(%p,%s,%lu,%s,%p): stub\n",This,debugstr_guid(rguidObject),dwIndex,debugstr_guid(rguidInterface),ppObject);
908
909         WARN("control unavailable\n");
910         return DSERR_CONTROLUNAVAIL;
911 }
912
913 static HRESULT WINAPI PrimaryBufferImpl_Initialize(
914         LPDIRECTSOUNDBUFFER8 iface,LPDIRECTSOUND8 dsound,LPDSBUFFERDESC dbsd
915 ) {
916         ICOM_THIS(PrimaryBufferImpl,iface);
917         FIXME("(%p,%p,%p):stub\n",This,dsound,dbsd);
918         DPRINTF("Re-Init!!!\n");
919         WARN("already initialized\n");
920         return DSERR_ALREADYINITIALIZED;
921 }
922
923 static HRESULT WINAPI PrimaryBufferImpl_GetCaps(
924         LPDIRECTSOUNDBUFFER8 iface,LPDSBCAPS caps
925 ) {
926         ICOM_THIS(PrimaryBufferImpl,iface);
927         TRACE("(%p)->(%p)\n",This,caps);
928
929         if (caps == NULL) {
930                 WARN("invalid parameter: caps == NULL\n");
931                 return DSERR_INVALIDPARAM;
932         }
933
934         if (caps->dwSize < sizeof(*caps)) {
935                 WARN("invalid parameter: caps->dwSize = %ld: < %d\n", caps->dwSize, sizeof(*caps));
936                 return DSERR_INVALIDPARAM;
937         }
938
939         caps->dwFlags = This->dsound->dsbd.dwFlags;
940         if (This->dsound->hwbuf) caps->dwFlags |= DSBCAPS_LOCHARDWARE;
941         else caps->dwFlags |= DSBCAPS_LOCSOFTWARE;
942
943         caps->dwBufferBytes = This->dsound->buflen;
944
945         /* This value represents the speed of the "unlock" command.
946            As unlock is quite fast (it does not do anything), I put
947            4096 ko/s = 4 Mo / s */
948         /* FIXME: hwbuf speed */
949         caps->dwUnlockTransferRate = 4096;
950         caps->dwPlayCpuOverhead = 0;
951
952         return DS_OK;
953 }
954
955 static HRESULT WINAPI PrimaryBufferImpl_QueryInterface(
956         LPDIRECTSOUNDBUFFER8 iface,REFIID riid,LPVOID *ppobj
957 ) {
958         ICOM_THIS(PrimaryBufferImpl,iface);
959         TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
960
961         if (ppobj == NULL) {
962                 WARN("invalid parameter\n");
963                 return E_INVALIDARG;
964         }
965
966         *ppobj = NULL;  /* assume failure */
967
968         if ( IsEqualGUID(riid, &IID_IUnknown) || 
969              IsEqualGUID(riid, &IID_IDirectSoundBuffer) ) {
970                 IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)This);
971                 *ppobj = This;
972                 return S_OK;
973         }
974
975         /* DirectSoundBuffer and DirectSoundBuffer8 are different and */
976         /* a primary buffer can't have a DirectSoundBuffer8 interface */
977         if ( IsEqualGUID( &IID_IDirectSoundBuffer8, riid ) ) {
978                 WARN("app requested DirectSoundBuffer8 on primary buffer\n");
979                 return E_NOINTERFACE;
980         }
981
982         if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
983                 ERR("app requested IDirectSoundNotify on primary buffer\n");
984                 /* FIXME: should we support this? */
985                 return E_NOINTERFACE;
986         }
987
988         if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
989                 ERR("app requested IDirectSound3DBuffer on primary buffer\n");
990                 return E_NOINTERFACE;
991         }
992
993         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
994                 if (!This->dsound->listener)
995                         IDirectSound3DListenerImpl_Create(This, &This->dsound->listener);
996                 if (This->dsound->listener) {
997                         *ppobj = This->dsound->listener;
998                         IDirectSound3DListener_AddRef((LPDIRECTSOUND3DLISTENER)*ppobj);
999                         return S_OK;
1000                 }
1001
1002                 WARN("IID_IDirectSound3DListener failed\n");
1003                 return E_NOINTERFACE;
1004         }
1005
1006         if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
1007                 FIXME("app requested IKsPropertySet on primary buffer\n");
1008                 return E_NOINTERFACE;
1009         }
1010
1011         FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
1012         return E_NOINTERFACE;
1013 }
1014
1015 static ICOM_VTABLE(IDirectSoundBuffer8) dspbvt =
1016 {
1017         ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
1018         PrimaryBufferImpl_QueryInterface,
1019         PrimaryBufferImpl_AddRef,
1020         PrimaryBufferImpl_Release,
1021         PrimaryBufferImpl_GetCaps,
1022         PrimaryBufferImpl_GetCurrentPosition,
1023         PrimaryBufferImpl_GetFormat,
1024         PrimaryBufferImpl_GetVolume,
1025         PrimaryBufferImpl_GetPan,
1026         PrimaryBufferImpl_GetFrequency,
1027         PrimaryBufferImpl_GetStatus,
1028         PrimaryBufferImpl_Initialize,
1029         PrimaryBufferImpl_Lock,
1030         PrimaryBufferImpl_Play,
1031         PrimaryBufferImpl_SetCurrentPosition,
1032         PrimaryBufferImpl_SetFormat,
1033         PrimaryBufferImpl_SetVolume,
1034         PrimaryBufferImpl_SetPan,
1035         PrimaryBufferImpl_SetFrequency,
1036         PrimaryBufferImpl_Stop,
1037         PrimaryBufferImpl_Unlock,
1038         PrimaryBufferImpl_Restore,
1039         PrimaryBufferImpl_SetFX,
1040         PrimaryBufferImpl_AcquireResources,
1041         PrimaryBufferImpl_GetObjectInPath
1042 };
1043
1044 HRESULT WINAPI PrimaryBufferImpl_Create(
1045         IDirectSoundImpl *ds,
1046         PrimaryBufferImpl **pdsb,
1047         LPDSBUFFERDESC dsbd)
1048 {
1049         PrimaryBufferImpl *dsb;
1050
1051         TRACE("%p,%p,%p)\n",ds,pdsb,dsbd);
1052
1053         if (dsbd->lpwfxFormat) {
1054                 WARN("invalid parameter: dsbd->lpwfxFormat != NULL\n");
1055                 *pdsb = NULL;
1056                 return DSERR_INVALIDPARAM;
1057         }
1058
1059         dsb = (PrimaryBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*dsb));
1060
1061         if (dsb == NULL) {
1062                 WARN("out of memory\n");
1063                 *pdsb = NULL;
1064                 return DSERR_OUTOFMEMORY;
1065         }
1066
1067         dsb->ref = 0;
1068         dsb->dsound = ds;
1069         dsb->lpVtbl = &dspbvt;
1070
1071         memcpy(&ds->dsbd, dsbd, sizeof(*dsbd));
1072
1073         TRACE("Created primary buffer at %p\n", dsb);
1074         TRACE("(formattag=0x%04x,chans=%d,samplerate=%ld,"
1075                 "bytespersec=%ld,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
1076                 ds->wfx.wFormatTag, ds->wfx.nChannels, ds->wfx.nSamplesPerSec,
1077                 ds->wfx.nAvgBytesPerSec, ds->wfx.nBlockAlign,
1078                 ds->wfx.wBitsPerSample, ds->wfx.cbSize);
1079
1080         IDirectSound_AddRef((LPDIRECTSOUND)ds);
1081         *pdsb = dsb;
1082         return S_OK;
1083 }