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