dsound: Handle failing of IDsDriver_CreateSoundBuffer better.
[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, falling back to waveout\n");
228                         /* Wine-only: close wine directsound driver, then reopen without WAVE_DIRECTSOUND */
229                         device->drvdesc.dwFlags = DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT;
230                         waveOutClose(device->hwo);
231                         IDsDriver_Release(device->driver);
232                         device->driver = device->buffer = NULL;
233                         device->hwo = 0;
234                         err = mmErr(waveOutOpen(&(device->hwo), device->drvdesc.dnDevNode, device->pwfx, (DWORD_PTR)DSOUND_callback, (DWORD)device, CALLBACK_FUNCTION));
235                         if (err != DS_OK)
236                         {
237                                 WARN("Falling back to waveout failed too! Giving up\n");
238                                 return err;
239                         }
240                 }
241         }
242
243         err = DSOUND_PrimaryOpen(device);
244
245         if (err != DS_OK) {
246                 WARN("DSOUND_PrimaryOpen failed\n");
247                 return err;
248         }
249
250         device->state = STATE_STOPPED;
251         return DS_OK;
252 }
253
254 HRESULT DSOUND_PrimaryDestroy(DirectSoundDevice *device)
255 {
256         TRACE("(%p)\n", device);
257
258         /* **** */
259         EnterCriticalSection(&(device->mixlock));
260
261         DSOUND_PrimaryClose(device);
262         if (device->driver) {
263                 if (device->hwbuf) {
264                         if (IDsDriverBuffer_Release(device->hwbuf) == 0)
265                                 device->hwbuf = 0;
266                 }
267         } else
268                 HeapFree(GetProcessHeap(),0,device->pwave);
269         HeapFree(GetProcessHeap(),0,device->pwfx);
270         device->pwfx=NULL;
271
272         LeaveCriticalSection(&(device->mixlock));
273         /* **** */
274
275         return DS_OK;
276 }
277
278 HRESULT DSOUND_PrimaryPlay(DirectSoundDevice *device)
279 {
280         HRESULT err = DS_OK;
281         TRACE("(%p)\n", device);
282
283         if (device->hwbuf) {
284                 err = IDsDriverBuffer_Play(device->hwbuf, 0, 0, DSBPLAY_LOOPING);
285                 if (err != DS_OK)
286                         WARN("IDsDriverBuffer_Play failed\n");
287         } else {
288                 err = mmErr(waveOutRestart(device->hwo));
289                 if (err != DS_OK)
290                         WARN("waveOutRestart failed\n");
291         }
292
293         return err;
294 }
295
296 HRESULT DSOUND_PrimaryStop(DirectSoundDevice *device)
297 {
298         HRESULT err = DS_OK;
299         TRACE("(%p)\n", device);
300
301         if (device->hwbuf) {
302                 err = IDsDriverBuffer_Stop(device->hwbuf);
303                 if (err == DSERR_BUFFERLOST) {
304                         DWORD flags = CALLBACK_FUNCTION | WAVE_DIRECTSOUND;
305                         /* Wine-only: the driver wants us to reopen the device */
306                         /* FIXME: check for errors */
307                         IDsDriverBuffer_Release(device->hwbuf);
308                         waveOutClose(device->hwo);
309                         device->hwo = 0;
310                         err = mmErr(waveOutOpen(&(device->hwo), device->drvdesc.dnDevNode,
311                                                 device->pwfx, (DWORD_PTR)DSOUND_callback, (DWORD)device,
312                                                 flags));
313                         if (err == DS_OK) {
314                                 device->playpos = 0;
315                                 device->mixpos = 0;
316                                 err = IDsDriver_CreateSoundBuffer(device->driver,device->pwfx,
317                                                                   DSBCAPS_PRIMARYBUFFER,0,
318                                                                   &(device->buflen),&(device->buffer),
319                                                                   (LPVOID)&(device->hwbuf));
320                                 if (err != DS_OK)
321                                         WARN("IDsDriver_CreateSoundBuffer failed\n");
322                                 else if (device->state == STATE_STOPPING)
323                                         device->state = STATE_STOPPED;
324                                 else if (device->state == STATE_PLAYING)
325                                         device->state = STATE_STARTING;
326                                 if (err == DS_OK)
327                                         FillMemory(device->buffer, device->buflen, (device->pwfx->wBitsPerSample == 8) ? 128 : 0);
328
329                         } else {
330                                 WARN("waveOutOpen failed\n");
331                         }
332                 } else if (err != DS_OK) {
333                         WARN("IDsDriverBuffer_Stop failed\n");
334                 }
335         } else {
336
337                 /* don't call the wave system with the lock set */
338                 LeaveCriticalSection(&(device->mixlock));
339                 /* **** */
340
341                 err = mmErr(waveOutPause(device->hwo));
342
343                 /* **** */
344                 EnterCriticalSection(&(device->mixlock));
345
346                 if (err != DS_OK)
347                         WARN("waveOutPause failed\n");
348         }
349
350         return err;
351 }
352
353 HRESULT DSOUND_PrimaryGetPosition(DirectSoundDevice *device, LPDWORD playpos, LPDWORD writepos)
354 {
355         TRACE("(%p,%p,%p)\n", device, playpos, writepos);
356
357         if (device->hwbuf) {
358                 HRESULT err=IDsDriverBuffer_GetPosition(device->hwbuf,playpos,writepos);
359                 if (err) {
360                         WARN("IDsDriverBuffer_GetPosition failed\n");
361                         return err;
362                 }
363         } else {
364
365                 /* check if playpos was requested */
366                 if (playpos) {
367                         /* use the cached play position */
368                         *playpos = device->pwplay * device->fraglen;
369                 }
370
371                 /* check if writepos was requested */
372                 if (writepos) {
373                         TRACE("pwplay=%i, pwqueue=%i\n", device->pwplay, device->pwqueue);
374
375                         /* the writepos is the first non-queued position */
376                         *writepos = (device->pwplay + device->pwqueue) * device->fraglen;
377                         *writepos %= device->buflen;
378                 }
379         }
380         TRACE("playpos = %d, writepos = %d (%p, time=%d)\n", playpos?*playpos:0, writepos?*writepos:0, device, GetTickCount());
381         return DS_OK;
382 }
383
384 HRESULT DSOUND_PrimarySetFormat(DirectSoundDevice *device, LPCWAVEFORMATEX wfex)
385 {
386         HRESULT err = DS_OK;
387         int i, alloc_size, cp_size;
388         DWORD nSamplesPerSec, bpp, chans;
389         TRACE("(%p,%p)\n", device, wfex);
390
391         if (device->priolevel == DSSCL_NORMAL) {
392                 WARN("failed priority check!\n");
393                 return DSERR_PRIOLEVELNEEDED;
394         }
395
396         /* Let's be pedantic! */
397         if (wfex == NULL) {
398                 WARN("invalid parameter: wfex==NULL!\n");
399                 return DSERR_INVALIDPARAM;
400         }
401         TRACE("(formattag=0x%04x,chans=%d,samplerate=%d,"
402               "bytespersec=%d,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
403               wfex->wFormatTag, wfex->nChannels, wfex->nSamplesPerSec,
404               wfex->nAvgBytesPerSec, wfex->nBlockAlign,
405               wfex->wBitsPerSample, wfex->cbSize);
406
407         /* **** */
408         RtlAcquireResourceExclusive(&(device->buffer_list_lock), TRUE);
409         EnterCriticalSection(&(device->mixlock));
410
411         if (wfex->wFormatTag == WAVE_FORMAT_PCM) {
412             alloc_size = sizeof(WAVEFORMATEX);
413             cp_size = sizeof(PCMWAVEFORMAT);
414         } else
415             alloc_size = cp_size = sizeof(WAVEFORMATEX) + wfex->cbSize;
416
417         device->pwfx = HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,device->pwfx,alloc_size);
418
419         nSamplesPerSec = device->pwfx->nSamplesPerSec;
420         bpp = device->pwfx->wBitsPerSample;
421         chans = device->pwfx->nChannels;
422
423         CopyMemory(device->pwfx, wfex, cp_size);
424
425         if (device->drvdesc.dwFlags & DSDDESC_DOMMSYSTEMSETFORMAT) {
426                 DWORD flags = CALLBACK_FUNCTION;
427                 if (device->driver)
428                         flags |= WAVE_DIRECTSOUND;
429                 /* FIXME: check for errors */
430                 DSOUND_PrimaryClose(device);
431                 waveOutClose(device->hwo);
432                 device->hwo = 0;
433                 err = mmErr(waveOutOpen(&(device->hwo), device->drvdesc.dnDevNode,
434                                         device->pwfx, (DWORD_PTR)DSOUND_callback, (DWORD)device,
435                                         flags));
436                 if (err == DS_OK) {
437                     err = DSOUND_PrimaryOpen(device);
438                     if (err != DS_OK) {
439                         WARN("DSOUND_PrimaryOpen failed\n");
440                         goto done;
441                     }
442                 } else {
443                         WARN("waveOutOpen failed\n");
444                         goto done;
445                 }
446         } else if (device->hwbuf) {
447                 err = IDsDriverBuffer_SetFormat(device->hwbuf, device->pwfx);
448                 if (err == DSERR_BUFFERLOST) {
449                         /* Wine-only: the driver wants us to recreate the HW buffer */
450                         IDsDriverBuffer_Release(device->hwbuf);
451                         device->playpos = 0;
452                         device->mixpos = 0;
453                         err = IDsDriver_CreateSoundBuffer(device->driver,device->pwfx,
454                                                           DSBCAPS_PRIMARYBUFFER,0,
455                                                           &(device->buflen),&(device->buffer),
456                                                           (LPVOID)&(device->hwbuf));
457                         if (err != DS_OK) {
458                                 WARN("IDsDriver_CreateSoundBuffer failed\n");
459                                 goto done;
460                         }
461                         if (device->state == STATE_PLAYING) device->state = STATE_STARTING;
462                         else if (device->state == STATE_STOPPING) device->state = STATE_STOPPED;
463                 } else if (FAILED(err)) {
464                         WARN("IDsDriverBuffer_SetFormat failed\n");
465                         goto done;
466                 }
467                 /* FIXME: should we set err back to DS_OK in all cases ? */
468                 DSOUND_RecalcPrimary(device);
469         }
470
471         if (nSamplesPerSec != device->pwfx->nSamplesPerSec || bpp != device->pwfx->wBitsPerSample || chans != device->pwfx->nChannels) {
472                 IDirectSoundBufferImpl** dsb = device->buffers;
473                 for (i = 0; i < device->nrofbuffers; i++, dsb++) {
474                         /* **** */
475                         RtlAcquireResourceExclusive(&(*dsb)->lock, TRUE);
476
477                         (*dsb)->freqAdjust = ((DWORD64)(*dsb)->freq << DSOUND_FREQSHIFT) / device->pwfx->nSamplesPerSec;
478                         DSOUND_RecalcFormat((*dsb));
479                         DSOUND_MixToTemporary((*dsb), 0, (*dsb)->buflen);
480
481                         RtlReleaseResource(&(*dsb)->lock);
482                         /* **** */
483                 }
484         }
485
486 done:
487         LeaveCriticalSection(&(device->mixlock));
488         RtlReleaseResource(&(device->buffer_list_lock));
489         /* **** */
490
491         return err;
492 }
493
494 /*******************************************************************************
495  *              PrimaryBuffer
496  */
497 /* This sets this format for the <em>Primary Buffer Only</em> */
498 /* See file:///cdrom/sdk52/docs/worddoc/dsound.doc page 120 */
499 static HRESULT WINAPI PrimaryBufferImpl_SetFormat(
500     LPDIRECTSOUNDBUFFER iface,
501     LPCWAVEFORMATEX wfex)
502 {
503     TRACE("(%p,%p)\n", iface, wfex);
504     return DSOUND_PrimarySetFormat(((PrimaryBufferImpl *)iface)->device, wfex);
505 }
506
507 static HRESULT WINAPI PrimaryBufferImpl_SetVolume(
508         LPDIRECTSOUNDBUFFER iface,LONG vol
509 ) {
510         DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
511         DWORD ampfactors;
512         DSVOLUMEPAN volpan;
513         HRESULT hres = DS_OK;
514         TRACE("(%p,%d)\n", iface, vol);
515
516         if (!(device->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
517                 WARN("control unavailable\n");
518                 return DSERR_CONTROLUNAVAIL;
519         }
520
521         if ((vol > DSBVOLUME_MAX) || (vol < DSBVOLUME_MIN)) {
522                 WARN("invalid parameter: vol = %d\n", vol);
523                 return DSERR_INVALIDPARAM;
524         }
525
526         /* **** */
527         EnterCriticalSection(&(device->mixlock));
528
529         waveOutGetVolume(device->hwo, &ampfactors);
530         volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
531         volpan.dwTotalRightAmpFactor=ampfactors >> 16;
532         DSOUND_AmpFactorToVolPan(&volpan);
533         if (vol != volpan.lVolume) {
534             volpan.lVolume=vol;
535             DSOUND_RecalcVolPan(&volpan);
536             if (device->hwbuf) {
537                 hres = IDsDriverBuffer_SetVolumePan(device->hwbuf, &volpan);
538                 if (hres != DS_OK)
539                     WARN("IDsDriverBuffer_SetVolumePan failed\n");
540             } else {
541                 ampfactors = (volpan.dwTotalLeftAmpFactor & 0xffff) | (volpan.dwTotalRightAmpFactor << 16);
542                 waveOutSetVolume(device->hwo, ampfactors);
543             }
544         }
545
546         LeaveCriticalSection(&(device->mixlock));
547         /* **** */
548
549         return hres;
550 }
551
552 static HRESULT WINAPI PrimaryBufferImpl_GetVolume(
553         LPDIRECTSOUNDBUFFER iface,LPLONG vol
554 ) {
555         DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
556         DWORD ampfactors;
557         DSVOLUMEPAN volpan;
558         TRACE("(%p,%p)\n", iface, vol);
559
560         if (!(device->dsbd.dwFlags & DSBCAPS_CTRLVOLUME)) {
561                 WARN("control unavailable\n");
562                 return DSERR_CONTROLUNAVAIL;
563         }
564
565         if (vol == NULL) {
566                 WARN("invalid parameter: vol = NULL\n");
567                 return DSERR_INVALIDPARAM;
568         }
569
570         waveOutGetVolume(device->hwo, &ampfactors);
571         volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
572         volpan.dwTotalRightAmpFactor=ampfactors >> 16;
573         DSOUND_AmpFactorToVolPan(&volpan);
574         *vol = volpan.lVolume;
575         return DS_OK;
576 }
577
578 static HRESULT WINAPI PrimaryBufferImpl_SetFrequency(
579         LPDIRECTSOUNDBUFFER iface,DWORD freq
580 ) {
581         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
582         TRACE("(%p,%d)\n",This,freq);
583
584         /* You cannot set the frequency of the primary buffer */
585         WARN("control unavailable\n");
586         return DSERR_CONTROLUNAVAIL;
587 }
588
589 static HRESULT WINAPI PrimaryBufferImpl_Play(
590         LPDIRECTSOUNDBUFFER iface,DWORD reserved1,DWORD reserved2,DWORD flags
591 ) {
592         DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
593         TRACE("(%p,%08x,%08x,%08x)\n", iface, reserved1, reserved2, flags);
594
595         if (!(flags & DSBPLAY_LOOPING)) {
596                 WARN("invalid parameter: flags = %08x\n", flags);
597                 return DSERR_INVALIDPARAM;
598         }
599
600         /* **** */
601         EnterCriticalSection(&(device->mixlock));
602
603         if (device->state == STATE_STOPPED)
604                 device->state = STATE_STARTING;
605         else if (device->state == STATE_STOPPING)
606                 device->state = STATE_PLAYING;
607
608         LeaveCriticalSection(&(device->mixlock));
609         /* **** */
610
611         return DS_OK;
612 }
613
614 static HRESULT WINAPI PrimaryBufferImpl_Stop(LPDIRECTSOUNDBUFFER iface)
615 {
616         DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
617         TRACE("(%p)\n", iface);
618
619         /* **** */
620         EnterCriticalSection(&(device->mixlock));
621
622         if (device->state == STATE_PLAYING)
623                 device->state = STATE_STOPPING;
624         else if (device->state == STATE_STARTING)
625                 device->state = STATE_STOPPED;
626
627         LeaveCriticalSection(&(device->mixlock));
628         /* **** */
629
630         return DS_OK;
631 }
632
633 static ULONG WINAPI PrimaryBufferImpl_AddRef(LPDIRECTSOUNDBUFFER iface)
634 {
635     PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
636     ULONG ref = InterlockedIncrement(&(This->ref));
637     TRACE("(%p) ref was %d\n", This, ref - 1);
638     return ref;
639 }
640
641 static ULONG WINAPI PrimaryBufferImpl_Release(LPDIRECTSOUNDBUFFER iface)
642 {
643     PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
644     DWORD ref = InterlockedDecrement(&(This->ref));
645     TRACE("(%p) ref was %d\n", This, ref + 1);
646
647     if (!ref) {
648         This->device->primary = NULL;
649         HeapFree(GetProcessHeap(), 0, This);
650         TRACE("(%p) released\n", This);
651     }
652     return ref;
653 }
654
655 static HRESULT WINAPI PrimaryBufferImpl_GetCurrentPosition(
656         LPDIRECTSOUNDBUFFER iface,LPDWORD playpos,LPDWORD writepos
657 ) {
658         HRESULT hres;
659         DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
660         TRACE("(%p,%p,%p)\n", iface, playpos, writepos);
661
662         /* **** */
663         EnterCriticalSection(&(device->mixlock));
664
665         hres = DSOUND_PrimaryGetPosition(device, playpos, writepos);
666         if (hres != DS_OK) {
667                 WARN("DSOUND_PrimaryGetPosition failed\n");
668                 LeaveCriticalSection(&(device->mixlock));
669                 return hres;
670         }
671         if (writepos) {
672                 if (device->state != STATE_STOPPED)
673                         /* apply the documented 10ms lead to writepos */
674                         *writepos += device->writelead;
675                 while (*writepos >= device->buflen) *writepos -= device->buflen;
676         }
677
678         LeaveCriticalSection(&(device->mixlock));
679         /* **** */
680
681         TRACE("playpos = %d, writepos = %d (%p, time=%d)\n", playpos?*playpos:0, writepos?*writepos:0, device, GetTickCount());
682         return DS_OK;
683 }
684
685 static HRESULT WINAPI PrimaryBufferImpl_GetStatus(
686         LPDIRECTSOUNDBUFFER iface,LPDWORD status
687 ) {
688         DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
689         TRACE("(%p,%p)\n", iface, status);
690
691         if (status == NULL) {
692                 WARN("invalid parameter: status == NULL\n");
693                 return DSERR_INVALIDPARAM;
694         }
695
696         *status = 0;
697         if ((device->state == STATE_STARTING) ||
698             (device->state == STATE_PLAYING))
699                 *status |= DSBSTATUS_PLAYING | DSBSTATUS_LOOPING;
700
701         TRACE("status=%x\n", *status);
702         return DS_OK;
703 }
704
705
706 static HRESULT WINAPI PrimaryBufferImpl_GetFormat(
707     LPDIRECTSOUNDBUFFER iface,
708     LPWAVEFORMATEX lpwf,
709     DWORD wfsize,
710     LPDWORD wfwritten)
711 {
712     DWORD size;
713     DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
714     TRACE("(%p,%p,%d,%p)\n", iface, lpwf, wfsize, wfwritten);
715
716     size = sizeof(WAVEFORMATEX) + device->pwfx->cbSize;
717
718     if (lpwf) { /* NULL is valid */
719         if (wfsize >= size) {
720             CopyMemory(lpwf,device->pwfx,size);
721             if (wfwritten)
722                 *wfwritten = size;
723         } else {
724             WARN("invalid parameter: wfsize too small\n");
725             if (wfwritten)
726                 *wfwritten = 0;
727             return DSERR_INVALIDPARAM;
728         }
729     } else {
730         if (wfwritten)
731             *wfwritten = sizeof(WAVEFORMATEX) + device->pwfx->cbSize;
732         else {
733             WARN("invalid parameter: wfwritten == NULL\n");
734             return DSERR_INVALIDPARAM;
735         }
736     }
737
738     return DS_OK;
739 }
740
741 static HRESULT WINAPI PrimaryBufferImpl_Lock(
742         LPDIRECTSOUNDBUFFER iface,DWORD writecursor,DWORD writebytes,LPVOID *lplpaudioptr1,LPDWORD audiobytes1,LPVOID *lplpaudioptr2,LPDWORD audiobytes2,DWORD flags
743 ) {
744         HRESULT hres;
745         DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
746         TRACE("(%p,%d,%d,%p,%p,%p,%p,0x%08x) at %d\n",
747                 iface,
748                 writecursor,
749                 writebytes,
750                 lplpaudioptr1,
751                 audiobytes1,
752                 lplpaudioptr2,
753                 audiobytes2,
754                 flags,
755                 GetTickCount()
756         );
757
758         if (device->priolevel != DSSCL_WRITEPRIMARY) {
759                 WARN("failed priority check!\n");
760                 return DSERR_PRIOLEVELNEEDED;
761         }
762
763         /* when this flag is set, writecursor is meaningless and must be calculated */
764         if (flags & DSBLOCK_FROMWRITECURSOR) {
765                 /* GetCurrentPosition does too much magic to duplicate here */
766                 hres = IDirectSoundBuffer_GetCurrentPosition(iface, NULL, &writecursor);
767                 if (hres != DS_OK) {
768                         WARN("IDirectSoundBuffer_GetCurrentPosition failed\n");
769                         return hres;
770                 }
771         }
772
773         /* when this flag is set, writebytes is meaningless and must be set */
774         if (flags & DSBLOCK_ENTIREBUFFER)
775                 writebytes = device->buflen;
776
777         if (writecursor >= device->buflen) {
778                 WARN("Invalid parameter, writecursor: %u >= buflen: %u\n",
779                      writecursor, device->buflen);
780                 return DSERR_INVALIDPARAM;
781         }
782
783         if (writebytes > device->buflen) {
784                 WARN("Invalid parameter, writebytes: %u > buflen: %u\n",
785                      writebytes, device->buflen);
786                 return DSERR_INVALIDPARAM;
787         }
788
789         if (!(device->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK) && device->hwbuf) {
790                 hres = IDsDriverBuffer_Lock(device->hwbuf,
791                                             lplpaudioptr1, audiobytes1,
792                                             lplpaudioptr2, audiobytes2,
793                                             writecursor, writebytes,
794                                             0);
795                 if (hres != DS_OK) {
796                         WARN("IDsDriverBuffer_Lock failed\n");
797                         return hres;
798                 }
799         } else {
800                 if (writecursor+writebytes <= device->buflen) {
801                         *(LPBYTE*)lplpaudioptr1 = device->buffer+writecursor;
802                         *audiobytes1 = writebytes;
803                         if (lplpaudioptr2)
804                                 *(LPBYTE*)lplpaudioptr2 = NULL;
805                         if (audiobytes2)
806                                 *audiobytes2 = 0;
807                         TRACE("->%d.0\n",writebytes);
808                 } else {
809                         *(LPBYTE*)lplpaudioptr1 = device->buffer+writecursor;
810                         *audiobytes1 = device->buflen-writecursor;
811                         if (lplpaudioptr2)
812                                 *(LPBYTE*)lplpaudioptr2 = device->buffer;
813                         if (audiobytes2)
814                                 *audiobytes2 = writebytes-(device->buflen-writecursor);
815                         TRACE("->%d.%d\n",*audiobytes1,audiobytes2?*audiobytes2:0);
816                 }
817         }
818         return DS_OK;
819 }
820
821 static HRESULT WINAPI PrimaryBufferImpl_SetCurrentPosition(
822         LPDIRECTSOUNDBUFFER iface,DWORD newpos
823 ) {
824         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
825         TRACE("(%p,%d)\n",This,newpos);
826
827         /* You cannot set the position of the primary buffer */
828         WARN("invalid call\n");
829         return DSERR_INVALIDCALL;
830 }
831
832 static HRESULT WINAPI PrimaryBufferImpl_SetPan(
833         LPDIRECTSOUNDBUFFER iface,LONG pan
834 ) {
835         DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
836         DWORD ampfactors;
837         DSVOLUMEPAN volpan;
838         HRESULT hres = DS_OK;
839         TRACE("(%p,%d)\n", iface, pan);
840
841         if (!(device->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
842                 WARN("control unavailable\n");
843                 return DSERR_CONTROLUNAVAIL;
844         }
845
846         if ((pan > DSBPAN_RIGHT) || (pan < DSBPAN_LEFT)) {
847                 WARN("invalid parameter: pan = %d\n", pan);
848                 return DSERR_INVALIDPARAM;
849         }
850
851         /* **** */
852         EnterCriticalSection(&(device->mixlock));
853
854         waveOutGetVolume(device->hwo, &ampfactors);
855         volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
856         volpan.dwTotalRightAmpFactor=ampfactors >> 16;
857         DSOUND_AmpFactorToVolPan(&volpan);
858         if (pan != volpan.lPan) {
859             volpan.lPan=pan;
860             DSOUND_RecalcVolPan(&volpan);
861             if (device->hwbuf) {
862                 hres = IDsDriverBuffer_SetVolumePan(device->hwbuf, &volpan);
863                 if (hres != DS_OK)
864                     WARN("IDsDriverBuffer_SetVolumePan failed\n");
865             } else {
866                 ampfactors = (volpan.dwTotalLeftAmpFactor & 0xffff) | (volpan.dwTotalRightAmpFactor << 16);
867                 waveOutSetVolume(device->hwo, ampfactors);
868             }
869         }
870
871         LeaveCriticalSection(&(device->mixlock));
872         /* **** */
873
874         return hres;
875 }
876
877 static HRESULT WINAPI PrimaryBufferImpl_GetPan(
878         LPDIRECTSOUNDBUFFER iface,LPLONG pan
879 ) {
880         DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
881         DWORD ampfactors;
882         DSVOLUMEPAN volpan;
883         TRACE("(%p,%p)\n", iface, pan);
884
885         if (!(device->dsbd.dwFlags & DSBCAPS_CTRLPAN)) {
886                 WARN("control unavailable\n");
887                 return DSERR_CONTROLUNAVAIL;
888         }
889
890         if (pan == NULL) {
891                 WARN("invalid parameter: pan == NULL\n");
892                 return DSERR_INVALIDPARAM;
893         }
894
895         waveOutGetVolume(device->hwo, &ampfactors);
896         volpan.dwTotalLeftAmpFactor=ampfactors & 0xffff;
897         volpan.dwTotalRightAmpFactor=ampfactors >> 16;
898         DSOUND_AmpFactorToVolPan(&volpan);
899         *pan = volpan.lPan;
900         return DS_OK;
901 }
902
903 static HRESULT WINAPI PrimaryBufferImpl_Unlock(
904         LPDIRECTSOUNDBUFFER iface,LPVOID p1,DWORD x1,LPVOID p2,DWORD x2
905 ) {
906         DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
907         TRACE("(%p,%p,%d,%p,%d)\n", iface, p1, x1, p2, x2);
908
909         if (device->priolevel != DSSCL_WRITEPRIMARY) {
910                 WARN("failed priority check!\n");
911                 return DSERR_PRIOLEVELNEEDED;
912         }
913
914         if (!(device->drvdesc.dwFlags & DSDDESC_DONTNEEDPRIMARYLOCK) && device->hwbuf) {
915                 HRESULT hres;
916                 
917                 hres = IDsDriverBuffer_Unlock(device->hwbuf, p1, x1, p2, x2);
918                 if (hres != DS_OK) {
919                         WARN("IDsDriverBuffer_Unlock failed\n");
920                         return hres;
921                 }
922         }
923
924         return DS_OK;
925 }
926
927 static HRESULT WINAPI PrimaryBufferImpl_Restore(
928         LPDIRECTSOUNDBUFFER iface
929 ) {
930         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
931         FIXME("(%p):stub\n",This);
932         return DS_OK;
933 }
934
935 static HRESULT WINAPI PrimaryBufferImpl_GetFrequency(
936         LPDIRECTSOUNDBUFFER iface,LPDWORD freq
937 ) {
938         DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
939         TRACE("(%p,%p)\n", iface, freq);
940
941         if (freq == NULL) {
942                 WARN("invalid parameter: freq == NULL\n");
943                 return DSERR_INVALIDPARAM;
944         }
945
946         if (!(device->dsbd.dwFlags & DSBCAPS_CTRLFREQUENCY)) {
947                 WARN("control unavailable\n");
948                 return DSERR_CONTROLUNAVAIL;
949         }
950
951         *freq = device->pwfx->nSamplesPerSec;
952         TRACE("-> %d\n", *freq);
953
954         return DS_OK;
955 }
956
957 static HRESULT WINAPI PrimaryBufferImpl_Initialize(
958         LPDIRECTSOUNDBUFFER iface,LPDIRECTSOUND dsound,LPCDSBUFFERDESC dbsd
959 ) {
960         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
961         WARN("(%p) already initialized\n", This);
962         return DSERR_ALREADYINITIALIZED;
963 }
964
965 static HRESULT WINAPI PrimaryBufferImpl_GetCaps(
966         LPDIRECTSOUNDBUFFER iface,LPDSBCAPS caps
967 ) {
968         DirectSoundDevice *device = ((PrimaryBufferImpl *)iface)->device;
969         TRACE("(%p,%p)\n", iface, caps);
970
971         if (caps == NULL) {
972                 WARN("invalid parameter: caps == NULL\n");
973                 return DSERR_INVALIDPARAM;
974         }
975
976         if (caps->dwSize < sizeof(*caps)) {
977                 WARN("invalid parameter: caps->dwSize = %d\n", caps->dwSize);
978                 return DSERR_INVALIDPARAM;
979         }
980
981         caps->dwFlags = device->dsbd.dwFlags;
982         if (device->hwbuf) caps->dwFlags |= DSBCAPS_LOCHARDWARE;
983         else caps->dwFlags |= DSBCAPS_LOCSOFTWARE;
984
985         caps->dwBufferBytes = device->buflen;
986
987         /* Windows reports these as zero */
988         caps->dwUnlockTransferRate = 0;
989         caps->dwPlayCpuOverhead = 0;
990
991         return DS_OK;
992 }
993
994 static HRESULT WINAPI PrimaryBufferImpl_QueryInterface(
995         LPDIRECTSOUNDBUFFER iface,REFIID riid,LPVOID *ppobj
996 ) {
997         PrimaryBufferImpl *This = (PrimaryBufferImpl *)iface;
998         DirectSoundDevice *device = This->device;
999         TRACE("(%p,%s,%p)\n", iface, debugstr_guid(riid), ppobj);
1000
1001         if (ppobj == NULL) {
1002                 WARN("invalid parameter\n");
1003                 return E_INVALIDARG;
1004         }
1005
1006         *ppobj = NULL;  /* assume failure */
1007
1008         if ( IsEqualGUID(riid, &IID_IUnknown) ||
1009              IsEqualGUID(riid, &IID_IDirectSoundBuffer) ) {
1010                 IDirectSoundBuffer_AddRef((LPDIRECTSOUNDBUFFER)This);
1011                 *ppobj = This;
1012                 return S_OK;
1013         }
1014
1015         /* DirectSoundBuffer and DirectSoundBuffer8 are different and */
1016         /* a primary buffer can't have a DirectSoundBuffer8 interface */
1017         if ( IsEqualGUID( &IID_IDirectSoundBuffer8, riid ) ) {
1018                 WARN("app requested DirectSoundBuffer8 on primary buffer\n");
1019                 return E_NOINTERFACE;
1020         }
1021
1022         if ( IsEqualGUID( &IID_IDirectSoundNotify, riid ) ) {
1023                 ERR("app requested IDirectSoundNotify on primary buffer\n");
1024                 /* FIXME: should we support this? */
1025                 return E_NOINTERFACE;
1026         }
1027
1028         if ( IsEqualGUID( &IID_IDirectSound3DBuffer, riid ) ) {
1029                 ERR("app requested IDirectSound3DBuffer on primary buffer\n");
1030                 return E_NOINTERFACE;
1031         }
1032
1033         if ( IsEqualGUID( &IID_IDirectSound3DListener, riid ) ) {
1034                 if (!device->listener)
1035                         IDirectSound3DListenerImpl_Create(device, &device->listener);
1036                 if (device->listener) {
1037                         *ppobj = device->listener;
1038                         IDirectSound3DListener_AddRef((LPDIRECTSOUND3DLISTENER)*ppobj);
1039                         return S_OK;
1040                 }
1041
1042                 WARN("IID_IDirectSound3DListener failed\n");
1043                 return E_NOINTERFACE;
1044         }
1045
1046         if ( IsEqualGUID( &IID_IKsPropertySet, riid ) ) {
1047                 FIXME("app requested IKsPropertySet on primary buffer\n");
1048                 return E_NOINTERFACE;
1049         }
1050
1051         FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
1052         return E_NOINTERFACE;
1053 }
1054
1055 static const IDirectSoundBufferVtbl dspbvt =
1056 {
1057         PrimaryBufferImpl_QueryInterface,
1058         PrimaryBufferImpl_AddRef,
1059         PrimaryBufferImpl_Release,
1060         PrimaryBufferImpl_GetCaps,
1061         PrimaryBufferImpl_GetCurrentPosition,
1062         PrimaryBufferImpl_GetFormat,
1063         PrimaryBufferImpl_GetVolume,
1064         PrimaryBufferImpl_GetPan,
1065         PrimaryBufferImpl_GetFrequency,
1066         PrimaryBufferImpl_GetStatus,
1067         PrimaryBufferImpl_Initialize,
1068         PrimaryBufferImpl_Lock,
1069         PrimaryBufferImpl_Play,
1070         PrimaryBufferImpl_SetCurrentPosition,
1071         PrimaryBufferImpl_SetFormat,
1072         PrimaryBufferImpl_SetVolume,
1073         PrimaryBufferImpl_SetPan,
1074         PrimaryBufferImpl_SetFrequency,
1075         PrimaryBufferImpl_Stop,
1076         PrimaryBufferImpl_Unlock,
1077         PrimaryBufferImpl_Restore
1078 };
1079
1080 HRESULT PrimaryBufferImpl_Create(
1081         DirectSoundDevice * device,
1082         PrimaryBufferImpl ** ppdsb,
1083         LPCDSBUFFERDESC dsbd)
1084 {
1085         PrimaryBufferImpl *dsb;
1086         TRACE("%p,%p,%p)\n",device,ppdsb,dsbd);
1087
1088         if (dsbd->lpwfxFormat) {
1089                 WARN("invalid parameter: dsbd->lpwfxFormat != NULL\n");
1090                 *ppdsb = NULL;
1091                 return DSERR_INVALIDPARAM;
1092         }
1093
1094         dsb = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*dsb));
1095
1096         if (dsb == NULL) {
1097                 WARN("out of memory\n");
1098                 *ppdsb = NULL;
1099                 return DSERR_OUTOFMEMORY;
1100         }
1101
1102         dsb->ref = 0;
1103         dsb->device = device;
1104         dsb->lpVtbl = &dspbvt;
1105
1106         CopyMemory(&device->dsbd, dsbd, sizeof(*dsbd));
1107
1108         TRACE("Created primary buffer at %p\n", dsb);
1109         TRACE("(formattag=0x%04x,chans=%d,samplerate=%d,"
1110                 "bytespersec=%d,blockalign=%d,bitspersamp=%d,cbSize=%d)\n",
1111                 device->pwfx->wFormatTag, device->pwfx->nChannels,
1112                 device->pwfx->nSamplesPerSec, device->pwfx->nAvgBytesPerSec,
1113                 device->pwfx->nBlockAlign, device->pwfx->wBitsPerSample,
1114                 device->pwfx->cbSize);
1115
1116         *ppdsb = dsb;
1117         return S_OK;
1118 }