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