Add support for more than one sound card.
[wine] / dlls / winmm / wineoss / dsrender.c
1 /*
2  * Sample Wine Driver for Open Sound System (featured in Linux and FreeBSD)
3  *
4  * Copyright 1994 Martin Ayotte
5  *           1999 Eric Pouech (async playing in waveOut/waveIn)
6  *           2000 Eric Pouech (loops in waveOut)
7  *           2002 Eric Pouech (full duplex)
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34 #include <errno.h>
35 #include <fcntl.h>
36 #ifdef HAVE_SYS_IOCTL_H
37 # include <sys/ioctl.h>
38 #endif
39 #ifdef HAVE_SYS_MMAN_H
40 # include <sys/mman.h>
41 #endif
42 #ifdef HAVE_POLL_H
43 #include <poll.h>
44 #endif
45 #ifdef HAVE_SYS_POLL_H
46 # include <sys/poll.h>
47 #endif
48
49 #include "windef.h"
50 #include "winbase.h"
51 #include "wingdi.h"
52 #include "winuser.h"
53 #include "winerror.h"
54 #include "mmddk.h"
55 #include "mmreg.h"
56 #include "dsound.h"
57 #include "dsdriver.h"
58 #include "oss.h"
59 #include "wine/debug.h"
60
61 #include "audio.h"
62
63 WINE_DEFAULT_DEBUG_CHANNEL(wave);
64
65 #ifdef HAVE_OSS
66
67 /*======================================================================*
68  *                  Low level DSOUND definitions                        *
69  *======================================================================*/
70
71 typedef struct IDsDriverPropertySetImpl IDsDriverPropertySetImpl;
72 typedef struct IDsDriverNotifyImpl IDsDriverNotifyImpl;
73 typedef struct IDsDriverImpl IDsDriverImpl;
74 typedef struct IDsDriverBufferImpl IDsDriverBufferImpl;
75
76 struct IDsDriverPropertySetImpl
77 {
78     /* IUnknown fields */
79     IDsDriverPropertySetVtbl   *lpVtbl;
80     DWORD                       ref;
81
82     IDsDriverBufferImpl*        buffer;
83 };
84
85 struct IDsDriverNotifyImpl
86 {
87     /* IUnknown fields */
88     IDsDriverNotifyVtbl        *lpVtbl;
89     DWORD                       ref;
90
91     /* IDsDriverNotifyImpl fields */
92     LPDSBPOSITIONNOTIFY         notifies;
93     int                         nrofnotifies;
94
95     IDsDriverBufferImpl*        buffer;
96 };
97
98 struct IDsDriverImpl
99 {
100     /* IUnknown fields */
101     IDsDriverVtbl              *lpVtbl;
102     DWORD                       ref;
103
104     /* IDsDriverImpl fields */
105     UINT                        wDevID;
106     IDsDriverBufferImpl*        primary;
107
108     int                         nrofsecondaries;
109     IDsDriverBufferImpl**       secondaries;
110 };
111
112 struct IDsDriverBufferImpl
113 {
114     /* IUnknown fields */
115     IDsDriverBufferVtbl        *lpVtbl;
116     DWORD                       ref;
117
118     /* IDsDriverBufferImpl fields */
119     IDsDriverImpl*              drv;
120     DWORD                       buflen;
121     WAVEFORMATPCMEX             wfex;
122     LPBYTE                      mapping;
123     DWORD                       maplen;
124     int                         fd;
125     DWORD                       dwFlags;
126
127     /* IDsDriverNotifyImpl fields */
128     IDsDriverNotifyImpl*        notify;
129     int                         notify_index;
130
131     /* IDsDriverPropertySetImpl fields */
132     IDsDriverPropertySetImpl*   property_set;
133 };
134
135 static HRESULT WINAPI IDsDriverPropertySetImpl_Create(
136     IDsDriverBufferImpl * dsdb,
137     IDsDriverPropertySetImpl **pdsdps);
138
139 static HRESULT WINAPI IDsDriverNotifyImpl_Create(
140     IDsDriverBufferImpl * dsdb,
141     IDsDriverNotifyImpl **pdsdn);
142
143 /*======================================================================*
144  *                  Low level DSOUND property set implementation        *
145  *======================================================================*/
146
147 static HRESULT WINAPI IDsDriverPropertySetImpl_QueryInterface(
148     PIDSDRIVERPROPERTYSET iface,
149     REFIID riid,
150     LPVOID *ppobj)
151 {
152     IDsDriverPropertySetImpl *This = (IDsDriverPropertySetImpl *)iface;
153     TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
154
155     if ( IsEqualGUID(riid, &IID_IUnknown) ||
156          IsEqualGUID(riid, &IID_IDsDriverPropertySet) ) {
157         IDsDriverPropertySet_AddRef(iface);
158         *ppobj = (LPVOID)This;
159         return DS_OK;
160     }
161
162     FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
163
164     *ppobj = 0;
165     return E_NOINTERFACE;
166 }
167
168 static ULONG WINAPI IDsDriverPropertySetImpl_AddRef(PIDSDRIVERPROPERTYSET iface)
169 {
170     IDsDriverPropertySetImpl *This = (IDsDriverPropertySetImpl *)iface;
171     ULONG refCount = InterlockedIncrement(&This->ref);
172
173     TRACE("(%p) ref was %ld\n", This, refCount - 1);
174
175     return refCount;
176 }
177
178 static ULONG WINAPI IDsDriverPropertySetImpl_Release(PIDSDRIVERPROPERTYSET iface)
179 {
180     IDsDriverPropertySetImpl *This = (IDsDriverPropertySetImpl *)iface;
181     ULONG refCount = InterlockedDecrement(&This->ref);
182
183     TRACE("(%p) ref was %ld\n", This, refCount + 1);
184
185     if (!refCount) {
186         IDsDriverBuffer_Release((PIDSDRIVERBUFFER)This->buffer);
187         HeapFree(GetProcessHeap(),0,This);
188         TRACE("(%p) released\n",This);
189     }
190     return refCount;
191 }
192
193 static HRESULT WINAPI IDsDriverPropertySetImpl_Get(
194     PIDSDRIVERPROPERTYSET iface,
195     PDSPROPERTY pDsProperty,
196     LPVOID pPropertyParams,
197     ULONG cbPropertyParams,
198     LPVOID pPropertyData,
199     ULONG cbPropertyData,
200     PULONG pcbReturnedData )
201 {
202     IDsDriverPropertySetImpl *This = (IDsDriverPropertySetImpl *)iface;
203     FIXME("(%p,%p,%p,%lx,%p,%lx,%p)\n",This,pDsProperty,pPropertyParams,cbPropertyParams,pPropertyData,cbPropertyData,pcbReturnedData);
204     return DSERR_UNSUPPORTED;
205 }
206
207 static HRESULT WINAPI IDsDriverPropertySetImpl_Set(
208     PIDSDRIVERPROPERTYSET iface,
209     PDSPROPERTY pDsProperty,
210     LPVOID pPropertyParams,
211     ULONG cbPropertyParams,
212     LPVOID pPropertyData,
213     ULONG cbPropertyData )
214 {
215     IDsDriverPropertySetImpl *This = (IDsDriverPropertySetImpl *)iface;
216     FIXME("(%p,%p,%p,%lx,%p,%lx)\n",This,pDsProperty,pPropertyParams,cbPropertyParams,pPropertyData,cbPropertyData);
217     return DSERR_UNSUPPORTED;
218 }
219
220 static HRESULT WINAPI IDsDriverPropertySetImpl_QuerySupport(
221     PIDSDRIVERPROPERTYSET iface,
222     REFGUID PropertySetId,
223     ULONG PropertyId,
224     PULONG pSupport )
225 {
226     IDsDriverPropertySetImpl *This = (IDsDriverPropertySetImpl *)iface;
227     FIXME("(%p,%s,%lx,%p)\n",This,debugstr_guid(PropertySetId),PropertyId,pSupport);
228     return DSERR_UNSUPPORTED;
229 }
230
231 IDsDriverPropertySetVtbl dsdpsvt =
232 {
233     IDsDriverPropertySetImpl_QueryInterface,
234     IDsDriverPropertySetImpl_AddRef,
235     IDsDriverPropertySetImpl_Release,
236     IDsDriverPropertySetImpl_Get,
237     IDsDriverPropertySetImpl_Set,
238     IDsDriverPropertySetImpl_QuerySupport,
239 };
240
241 /*======================================================================*
242  *                  Low level DSOUND notify implementation              *
243  *======================================================================*/
244
245 static HRESULT WINAPI IDsDriverNotifyImpl_QueryInterface(
246     PIDSDRIVERNOTIFY iface,
247     REFIID riid,
248     LPVOID *ppobj)
249 {
250     IDsDriverNotifyImpl *This = (IDsDriverNotifyImpl *)iface;
251     TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
252
253     if ( IsEqualGUID(riid, &IID_IUnknown) ||
254          IsEqualGUID(riid, &IID_IDsDriverNotify) ) {
255         IDsDriverNotify_AddRef(iface);
256         *ppobj = This;
257         return DS_OK;
258     }
259
260     FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
261
262     *ppobj = 0;
263     return E_NOINTERFACE;
264 }
265
266 static ULONG WINAPI IDsDriverNotifyImpl_AddRef(PIDSDRIVERNOTIFY iface)
267 {
268     IDsDriverNotifyImpl *This = (IDsDriverNotifyImpl *)iface;
269     ULONG refCount = InterlockedIncrement(&This->ref);
270
271     TRACE("(%p) ref was %ld\n", This, refCount - 1);
272
273     return refCount;
274 }
275
276 static ULONG WINAPI IDsDriverNotifyImpl_Release(PIDSDRIVERNOTIFY iface)
277 {
278     IDsDriverNotifyImpl *This = (IDsDriverNotifyImpl *)iface;
279     ULONG refCount = InterlockedDecrement(&This->ref);
280
281     TRACE("(%p) ref was %ld\n", This, refCount + 1);
282
283     if (!refCount) {
284         IDsDriverBuffer_Release((PIDSDRIVERBUFFER)This->buffer);
285         HeapFree(GetProcessHeap(), 0, This->notifies);
286         HeapFree(GetProcessHeap(),0,This);
287         TRACE("(%p) released\n",This);
288     }
289     return refCount;
290 }
291
292 static HRESULT WINAPI IDsDriverNotifyImpl_SetNotificationPositions(
293     PIDSDRIVERNOTIFY iface,
294     DWORD howmuch,
295     LPCDSBPOSITIONNOTIFY notify)
296 {
297     IDsDriverNotifyImpl *This = (IDsDriverNotifyImpl *)iface;
298     TRACE("(%p,0x%08lx,%p)\n",This,howmuch,notify);
299
300     if (!notify) {
301         WARN("invalid parameter\n");
302         return DSERR_INVALIDPARAM;
303     }
304
305     if (TRACE_ON(wave)) {
306         int i;
307         for (i=0;i<howmuch;i++)
308             TRACE("notify at %ld to 0x%08lx\n",
309                 notify[i].dwOffset,(DWORD)notify[i].hEventNotify);
310     }
311
312     /* Make an internal copy of the caller-supplied array.
313      * Replace the existing copy if one is already present. */
314     if (This->notifies)
315         This->notifies = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
316         This->notifies, howmuch * sizeof(DSBPOSITIONNOTIFY));
317     else
318         This->notifies = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
319         howmuch * sizeof(DSBPOSITIONNOTIFY));
320
321     memcpy(This->notifies, notify, howmuch * sizeof(DSBPOSITIONNOTIFY));
322     This->nrofnotifies = howmuch;
323
324     return S_OK;
325 }
326
327 IDsDriverNotifyVtbl dsdnvt =
328 {
329     IDsDriverNotifyImpl_QueryInterface,
330     IDsDriverNotifyImpl_AddRef,
331     IDsDriverNotifyImpl_Release,
332     IDsDriverNotifyImpl_SetNotificationPositions,
333 };
334
335 /*======================================================================*
336  *                  Low level DSOUND implementation                     *
337  *======================================================================*/
338
339 static HRESULT DSDB_MapBuffer(IDsDriverBufferImpl *dsdb)
340 {
341     TRACE("(%p), format=%ldx%dx%d\n", dsdb, dsdb->wfex.Format.nSamplesPerSec,
342           dsdb->wfex.Format.wBitsPerSample, dsdb->wfex.Format.nChannels);
343     if (!dsdb->mapping) {
344         dsdb->mapping = mmap(NULL, dsdb->maplen, PROT_WRITE, MAP_SHARED,
345                              dsdb->fd, 0);
346         if (dsdb->mapping == (LPBYTE)-1) {
347             ERR("Could not map sound device for direct access (%s)\n", strerror(errno));
348             ERR("Use: \"HardwareAcceleration\" = \"Emulation\" in the [dsound] section of your config file.\n");
349             return DSERR_GENERIC;
350         }
351         TRACE("The sound device has been mapped for direct access at %p, size=%ld\n", dsdb->mapping, dsdb->maplen);
352
353         /* for some reason, es1371 and sblive! sometimes have junk in here.
354          * clear it, or we get junk noise */
355         /* some libc implementations are buggy: their memset reads from the buffer...
356          * to work around it, we have to zero the block by hand. We don't do the expected:
357          * memset(dsdb->mapping,0, dsdb->maplen);
358          */
359         {
360             unsigned char*      p1 = dsdb->mapping;
361             unsigned            len = dsdb->maplen;
362             unsigned char       silence = (dsdb->wfex.Format.wBitsPerSample == 8) ? 128 : 0;
363             unsigned long       ulsilence = (dsdb->wfex.Format.wBitsPerSample == 8) ? 0x80808080 : 0;
364
365             if (len >= 16) /* so we can have at least a 4 long area to store... */
366             {
367                 /* the mmap:ed value is (at least) dword aligned
368                  * so, start filling the complete unsigned long:s
369                  */
370                 int             b = len >> 2;
371                 unsigned long*  p4 = (unsigned long*)p1;
372
373                 while (b--) *p4++ = ulsilence;
374                 /* prepare for filling the rest */
375                 len &= 3;
376                 p1 = (unsigned char*)p4;
377             }
378             /* in all cases, fill the remaining bytes */
379             while (len-- != 0) *p1++ = silence;
380         }
381     }
382     return DS_OK;
383 }
384
385 static HRESULT DSDB_UnmapBuffer(IDsDriverBufferImpl *dsdb)
386 {
387     TRACE("(%p)\n",dsdb);
388     if (dsdb->mapping) {
389         if (munmap(dsdb->mapping, dsdb->maplen) < 0) {
390             ERR("(%p): Could not unmap sound device (%s)\n", dsdb, strerror(errno));
391             return DSERR_GENERIC;
392         }
393         dsdb->mapping = NULL;
394         TRACE("(%p): sound device unmapped\n", dsdb);
395     }
396     return DS_OK;
397 }
398
399 static HRESULT WINAPI IDsDriverBufferImpl_QueryInterface(PIDSDRIVERBUFFER iface, REFIID riid, LPVOID *ppobj)
400 {
401     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
402     TRACE("(%p,%s,%p)\n",iface,debugstr_guid(riid),*ppobj);
403
404     if ( IsEqualGUID(riid, &IID_IUnknown) ||
405          IsEqualGUID(riid, &IID_IDsDriverBuffer) ) {
406         IDsDriverBuffer_AddRef(iface);
407         *ppobj = (LPVOID)This;
408         return DS_OK;
409     }
410
411     if ( IsEqualGUID( &IID_IDsDriverNotify, riid ) ) {
412         if (!This->notify)
413             IDsDriverNotifyImpl_Create(This, &(This->notify));
414         if (This->notify) {
415             IDsDriverNotify_AddRef((PIDSDRIVERNOTIFY)This->notify);
416             *ppobj = (LPVOID)This->notify;
417             return DS_OK;
418         }
419         *ppobj = 0;
420         return E_FAIL;
421     }
422
423     if ( IsEqualGUID( &IID_IDsDriverPropertySet, riid ) ) {
424         if (!This->property_set)
425             IDsDriverPropertySetImpl_Create(This, &(This->property_set));
426         if (This->property_set) {
427             IDsDriverPropertySet_AddRef((PIDSDRIVERPROPERTYSET)This->property_set);
428             *ppobj = (LPVOID)This->property_set;
429             return DS_OK;
430         }
431         *ppobj = 0;
432         return E_FAIL;
433     }
434
435     FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
436
437     *ppobj = 0;
438
439     return E_NOINTERFACE;
440 }
441
442 static ULONG WINAPI IDsDriverBufferImpl_AddRef(PIDSDRIVERBUFFER iface)
443 {
444     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
445     ULONG refCount = InterlockedIncrement(&This->ref);
446
447     TRACE("(%p) ref was %ld\n", This, refCount - 1);
448
449     return refCount;
450 }
451
452 static ULONG WINAPI IDsDriverBufferImpl_Release(PIDSDRIVERBUFFER iface)
453 {
454     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
455     ULONG refCount = InterlockedDecrement(&This->ref);
456
457     TRACE("(%p) ref was %ld\n", This, refCount + 1);
458
459     if (refCount)
460         return refCount;
461
462     if (This == This->drv->primary)
463         This->drv->primary = NULL;
464     else {
465         int i;
466         for (i = 0; i < This->drv->nrofsecondaries; i++)
467             if (This->drv->secondaries[i] == This)
468                 break;
469         if (i < This->drv->nrofsecondaries) {
470             /* Put the last buffer of the list in the (now empty) position */
471             This->drv->secondaries[i] = This->drv->secondaries[This->drv->nrofsecondaries - 1];
472             This->drv->nrofsecondaries--;
473             This->drv->secondaries = HeapReAlloc(GetProcessHeap(),0,
474                 This->drv->secondaries,
475                 sizeof(PIDSDRIVERBUFFER)*This->drv->nrofsecondaries);
476             TRACE("(%p) buffer count is now %d\n", This, This->drv->nrofsecondaries);
477         }
478
479         WOutDev[This->drv->wDevID].ossdev->ds_caps.dwFreeHwMixingAllBuffers++;
480         WOutDev[This->drv->wDevID].ossdev->ds_caps.dwFreeHwMixingStreamingBuffers++;
481     }
482
483     DSDB_UnmapBuffer(This);
484     HeapFree(GetProcessHeap(),0,This);
485     TRACE("(%p) released\n",This);
486     return 0;
487 }
488
489 static HRESULT WINAPI IDsDriverBufferImpl_Lock(PIDSDRIVERBUFFER iface,
490                                                LPVOID*ppvAudio1,LPDWORD pdwLen1,
491                                                LPVOID*ppvAudio2,LPDWORD pdwLen2,
492                                                DWORD dwWritePosition,DWORD dwWriteLen,
493                                                DWORD dwFlags)
494 {
495     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
496     /* since we (GetDriverDesc flags) have specified DSDDESC_DONTNEEDPRIMARYLOCK,
497      * and that we don't support secondary buffers, this method will never be called */
498     TRACE("(%p): stub\n",iface);
499     return DSERR_UNSUPPORTED;
500 }
501
502 static HRESULT WINAPI IDsDriverBufferImpl_Unlock(PIDSDRIVERBUFFER iface,
503                                                  LPVOID pvAudio1,DWORD dwLen1,
504                                                  LPVOID pvAudio2,DWORD dwLen2)
505 {
506     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
507     TRACE("(%p): stub\n",iface);
508     return DSERR_UNSUPPORTED;
509 }
510
511 static HRESULT WINAPI IDsDriverBufferImpl_SetFormat(PIDSDRIVERBUFFER iface,
512                                                     LPWAVEFORMATEX pwfx)
513 {
514     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
515
516     TRACE("(%p,%p)\n",iface,pwfx);
517     /* On our request (GetDriverDesc flags), DirectSound has by now used
518      * waveOutClose/waveOutOpen to set the format...
519      * unfortunately, this means our mmap() is now gone...
520      * so we need to somehow signal to our DirectSound implementation
521      * that it should completely recreate this HW buffer...
522      * this unexpected error code should do the trick... */
523     return DSERR_BUFFERLOST;
524 }
525
526 static HRESULT WINAPI IDsDriverBufferImpl_SetFrequency(PIDSDRIVERBUFFER iface, DWORD dwFreq)
527 {
528     /* IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface; */
529     TRACE("(%p,%ld): stub\n",iface,dwFreq);
530     return DSERR_UNSUPPORTED;
531 }
532
533 static HRESULT WINAPI IDsDriverBufferImpl_SetVolumePan(PIDSDRIVERBUFFER iface, PDSVOLUMEPAN pVolPan)
534 {
535     DWORD vol;
536     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
537     TRACE("(%p,%p)\n",This,pVolPan);
538
539     vol = pVolPan->dwTotalLeftAmpFactor | (pVolPan->dwTotalRightAmpFactor << 16);
540
541     if (wodSetVolume(This->drv->wDevID, vol) != MMSYSERR_NOERROR) {
542         WARN("wodSetVolume failed\n");
543         return DSERR_INVALIDPARAM;
544     }
545
546     return DS_OK;
547 }
548
549 static HRESULT WINAPI IDsDriverBufferImpl_SetPosition(PIDSDRIVERBUFFER iface, DWORD dwNewPos)
550 {
551     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
552     TRACE("(%p,%ld): stub\n",iface,dwNewPos);
553     return DSERR_UNSUPPORTED;
554 }
555
556 static HRESULT WINAPI IDsDriverBufferImpl_GetPosition(PIDSDRIVERBUFFER iface,
557                                                       LPDWORD lpdwPlay, LPDWORD lpdwWrite)
558 {
559     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
560     count_info info;
561     DWORD ptr;
562
563     TRACE("(%p)\n",iface);
564     if (WOutDev[This->drv->wDevID].state == WINE_WS_CLOSED) {
565         ERR("device not open, but accessing?\n");
566         return DSERR_UNINITIALIZED;
567     }
568     if (ioctl(This->fd, SNDCTL_DSP_GETOPTR, &info) < 0) {
569         ERR("ioctl(%s, SNDCTL_DSP_GETOPTR) failed (%s)\n",
570             WOutDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
571         return DSERR_GENERIC;
572     }
573     ptr = info.ptr & ~3; /* align the pointer, just in case */
574     if (lpdwPlay) *lpdwPlay = ptr;
575     if (lpdwWrite) {
576         /* add some safety margin (not strictly necessary, but...) */
577         if (WOutDev[This->drv->wDevID].ossdev->duplex_out_caps.dwSupport & WAVECAPS_SAMPLEACCURATE)
578             *lpdwWrite = ptr + 32;
579         else
580             *lpdwWrite = ptr + WOutDev[This->drv->wDevID].dwFragmentSize;
581         while (*lpdwWrite > This->buflen)
582             *lpdwWrite -= This->buflen;
583     }
584     TRACE("playpos=%ld, writepos=%ld\n", lpdwPlay?*lpdwPlay:0, lpdwWrite?*lpdwWrite:0);
585     return DS_OK;
586 }
587
588 static HRESULT WINAPI IDsDriverBufferImpl_Play(PIDSDRIVERBUFFER iface, DWORD dwRes1, DWORD dwRes2, DWORD dwFlags)
589 {
590     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
591     int enable;
592     TRACE("(%p,%lx,%lx,%lx)\n",iface,dwRes1,dwRes2,dwFlags);
593     WOutDev[This->drv->wDevID].ossdev->bOutputEnabled = TRUE;
594     enable = getEnables(WOutDev[This->drv->wDevID].ossdev);
595     if (ioctl(This->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
596         if (errno == EINVAL) {
597             /* Don't give up yet. OSS trigger support is inconsistent. */
598             if (WOutDev[This->drv->wDevID].ossdev->open_count == 1) {
599                 /* try the opposite input enable */
600                 if (WOutDev[This->drv->wDevID].ossdev->bInputEnabled == FALSE)
601                     WOutDev[This->drv->wDevID].ossdev->bInputEnabled = TRUE;
602                 else
603                     WOutDev[This->drv->wDevID].ossdev->bInputEnabled = FALSE;
604                 /* try it again */
605                 enable = getEnables(WOutDev[This->drv->wDevID].ossdev);
606                 if (ioctl(This->fd, SNDCTL_DSP_SETTRIGGER, &enable) >= 0)
607                     return DS_OK;
608             }
609         }
610         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n",
611             WOutDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
612         WOutDev[This->drv->wDevID].ossdev->bOutputEnabled = FALSE;
613         return DSERR_GENERIC;
614     }
615     return DS_OK;
616 }
617
618 static HRESULT WINAPI IDsDriverBufferImpl_Stop(PIDSDRIVERBUFFER iface)
619 {
620     IDsDriverBufferImpl *This = (IDsDriverBufferImpl *)iface;
621     int enable;
622     TRACE("(%p)\n",iface);
623     /* no more playing */
624     WOutDev[This->drv->wDevID].ossdev->bOutputEnabled = FALSE;
625     enable = getEnables(WOutDev[This->drv->wDevID].ossdev);
626     if (ioctl(This->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
627         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n", WOutDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
628         return DSERR_GENERIC;
629     }
630 #if 0
631     /* the play position must be reset to the beginning of the buffer */
632     if (ioctl(This->fd, SNDCTL_DSP_RESET, 0) < 0) {
633         ERR("ioctl(%s, SNDCTL_DSP_RESET) failed (%s)\n", WOutDev[This->drv->wDevID].ossdev->dev_name, strerror(errno));
634         return DSERR_GENERIC;
635     }
636 #endif
637     /* Most OSS drivers just can't stop the playback without closing the device...
638      * so we need to somehow signal to our DirectSound implementation
639      * that it should completely recreate this HW buffer...
640      * this unexpected error code should do the trick... */
641     /* FIXME: ...unless we are doing full duplex, then it's not nice to close the device */
642     if (WOutDev[This->drv->wDevID].ossdev->open_count == 1)
643         return DSERR_BUFFERLOST;
644
645     return DS_OK;
646 }
647
648 static IDsDriverBufferVtbl dsdbvt =
649 {
650     IDsDriverBufferImpl_QueryInterface,
651     IDsDriverBufferImpl_AddRef,
652     IDsDriverBufferImpl_Release,
653     IDsDriverBufferImpl_Lock,
654     IDsDriverBufferImpl_Unlock,
655     IDsDriverBufferImpl_SetFormat,
656     IDsDriverBufferImpl_SetFrequency,
657     IDsDriverBufferImpl_SetVolumePan,
658     IDsDriverBufferImpl_SetPosition,
659     IDsDriverBufferImpl_GetPosition,
660     IDsDriverBufferImpl_Play,
661     IDsDriverBufferImpl_Stop
662 };
663
664 static HRESULT WINAPI IDsDriverImpl_QueryInterface(PIDSDRIVER iface, REFIID riid, LPVOID *ppobj)
665 {
666     IDsDriverImpl *This = (IDsDriverImpl *)iface;
667     TRACE("(%p,%s,%p)\n",This,debugstr_guid(riid),ppobj);
668
669     if ( IsEqualGUID(riid, &IID_IUnknown) ||
670          IsEqualGUID(riid, &IID_IDsDriver) ) {
671         IDsDriver_AddRef(iface);
672         *ppobj = (LPVOID)This;
673         return DS_OK;
674     }
675
676     FIXME( "Unknown IID %s\n", debugstr_guid( riid ) );
677
678     *ppobj = 0;
679
680     return E_NOINTERFACE;
681 }
682
683 static ULONG WINAPI IDsDriverImpl_AddRef(PIDSDRIVER iface)
684 {
685     IDsDriverImpl *This = (IDsDriverImpl *)iface;
686     ULONG refCount = InterlockedIncrement(&This->ref);
687
688     TRACE("(%p) ref was %ld\n", This, refCount - 1);
689
690     return refCount;
691 }
692
693 static ULONG WINAPI IDsDriverImpl_Release(PIDSDRIVER iface)
694 {
695     IDsDriverImpl *This = (IDsDriverImpl *)iface;
696     ULONG refCount = InterlockedDecrement(&This->ref);
697
698     TRACE("(%p) ref was %ld\n", This, refCount + 1);
699
700     if (!refCount) {
701         HeapFree(GetProcessHeap(),0,This);
702         TRACE("(%p) released\n",This);
703     }
704     return refCount;
705 }
706
707 static HRESULT WINAPI IDsDriverImpl_GetDriverDesc(PIDSDRIVER iface,
708                                                   PDSDRIVERDESC pDesc)
709 {
710     IDsDriverImpl *This = (IDsDriverImpl *)iface;
711     TRACE("(%p,%p)\n",iface,pDesc);
712
713     /* copy version from driver */
714     memcpy(pDesc, &(WOutDev[This->wDevID].ossdev->ds_desc), sizeof(DSDRIVERDESC));
715
716     pDesc->dwFlags |= DSDDESC_DOMMSYSTEMOPEN | DSDDESC_DOMMSYSTEMSETFORMAT |
717         DSDDESC_USESYSTEMMEMORY | DSDDESC_DONTNEEDPRIMARYLOCK |
718         DSDDESC_DONTNEEDSECONDARYLOCK;
719     pDesc->dnDevNode            = WOutDev[This->wDevID].waveDesc.dnDevNode;
720     pDesc->wVxdId               = 0;
721     pDesc->wReserved            = 0;
722     pDesc->ulDeviceNum          = This->wDevID;
723     pDesc->dwHeapType           = DSDHEAP_NOHEAP;
724     pDesc->pvDirectDrawHeap     = NULL;
725     pDesc->dwMemStartAddress    = 0;
726     pDesc->dwMemEndAddress      = 0;
727     pDesc->dwMemAllocExtra      = 0;
728     pDesc->pvReserved1          = NULL;
729     pDesc->pvReserved2          = NULL;
730     return DS_OK;
731 }
732
733 static HRESULT WINAPI IDsDriverImpl_Open(PIDSDRIVER iface)
734 {
735     IDsDriverImpl *This = (IDsDriverImpl *)iface;
736     int enable;
737     TRACE("(%p)\n",iface);
738
739     /* make sure the card doesn't start playing before we want it to */
740     WOutDev[This->wDevID].ossdev->bOutputEnabled = FALSE;
741     WOutDev[This->wDevID].ossdev->bInputEnabled = FALSE;
742     enable = getEnables(WOutDev[This->wDevID].ossdev);
743     if (ioctl(WOutDev[This->wDevID].ossdev->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
744         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n",WOutDev[This->wDevID].ossdev->dev_name, strerror(errno));
745         return DSERR_GENERIC;
746     }
747     return DS_OK;
748 }
749
750 static HRESULT WINAPI IDsDriverImpl_Close(PIDSDRIVER iface)
751 {
752     IDsDriverImpl *This = (IDsDriverImpl *)iface;
753     TRACE("(%p)\n",iface);
754     if (This->primary) {
755         ERR("problem with DirectSound: primary not released\n");
756         return DSERR_GENERIC;
757     }
758     return DS_OK;
759 }
760
761 static HRESULT WINAPI IDsDriverImpl_GetCaps(PIDSDRIVER iface, PDSDRIVERCAPS pCaps)
762 {
763     IDsDriverImpl *This = (IDsDriverImpl *)iface;
764     TRACE("(%p,%p)\n",iface,pCaps);
765     memcpy(pCaps, &(WOutDev[This->wDevID].ossdev->ds_caps), sizeof(DSDRIVERCAPS));
766     return DS_OK;
767 }
768
769 static HRESULT WINAPI DSD_CreatePrimaryBuffer(PIDSDRIVER iface,
770                                               LPWAVEFORMATEX pwfx,
771                                               DWORD dwFlags,
772                                               DWORD dwCardAddress,
773                                               LPDWORD pdwcbBufferSize,
774                                               LPBYTE *ppbBuffer,
775                                               LPVOID *ppvObj)
776 {
777     IDsDriverImpl *This = (IDsDriverImpl *)iface;
778     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
779     HRESULT err;
780     audio_buf_info info;
781     int enable = 0;
782     TRACE("(%p,%p,%lx,%lx,%p,%p,%p)\n",iface,pwfx,dwFlags,dwCardAddress,pdwcbBufferSize,ppbBuffer,ppvObj);
783
784     if (This->primary)
785         return DSERR_ALLOCATED;
786     if (dwFlags & (DSBCAPS_CTRLFREQUENCY | DSBCAPS_CTRLPAN))
787         return DSERR_CONTROLUNAVAIL;
788
789     *ippdsdb = (IDsDriverBufferImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDsDriverBufferImpl));
790     if (*ippdsdb == NULL)
791         return DSERR_OUTOFMEMORY;
792     (*ippdsdb)->lpVtbl  = &dsdbvt;
793     (*ippdsdb)->ref     = 1;
794     (*ippdsdb)->drv     = This;
795     copy_format(pwfx, &(*ippdsdb)->wfex);
796     (*ippdsdb)->fd      = WOutDev[This->wDevID].ossdev->fd;
797     (*ippdsdb)->dwFlags = dwFlags;
798
799     /* check how big the DMA buffer is now */
800     if (ioctl((*ippdsdb)->fd, SNDCTL_DSP_GETOSPACE, &info) < 0) {
801         ERR("ioctl(%s, SNDCTL_DSP_GETOSPACE) failed (%s)\n",
802             WOutDev[This->wDevID].ossdev->dev_name, strerror(errno));
803         HeapFree(GetProcessHeap(),0,*ippdsdb);
804         *ippdsdb = NULL;
805         return DSERR_GENERIC;
806     }
807     (*ippdsdb)->maplen = (*ippdsdb)->buflen = info.fragstotal * info.fragsize;
808
809     /* map the DMA buffer */
810     err = DSDB_MapBuffer(*ippdsdb);
811     if (err != DS_OK) {
812         HeapFree(GetProcessHeap(),0,*ippdsdb);
813         *ippdsdb = NULL;
814         return err;
815     }
816
817     /* primary buffer is ready to go */
818     *pdwcbBufferSize    = (*ippdsdb)->maplen;
819     *ppbBuffer          = (*ippdsdb)->mapping;
820
821     /* some drivers need some extra nudging after mapping */
822     WOutDev[This->wDevID].ossdev->bInputEnabled = FALSE;
823     WOutDev[This->wDevID].ossdev->bOutputEnabled = FALSE;
824     enable = getEnables(WOutDev[This->wDevID].ossdev);
825     if (ioctl((*ippdsdb)->fd, SNDCTL_DSP_SETTRIGGER, &enable) < 0) {
826         ERR("ioctl(%s, SNDCTL_DSP_SETTRIGGER) failed (%s)\n",
827             WOutDev[This->wDevID].ossdev->dev_name, strerror(errno));
828         return DSERR_GENERIC;
829     }
830
831     This->primary = *ippdsdb;
832
833     return DS_OK;
834 }
835
836 static HRESULT WINAPI DSD_CreateSecondaryBuffer(PIDSDRIVER iface,
837                                                 LPWAVEFORMATEX pwfx,
838                                                 DWORD dwFlags,
839                                                 DWORD dwCardAddress,
840                                                 LPDWORD pdwcbBufferSize,
841                                                 LPBYTE *ppbBuffer,
842                                                 LPVOID *ppvObj)
843 {
844     IDsDriverImpl *This = (IDsDriverImpl *)iface;
845     IDsDriverBufferImpl** ippdsdb = (IDsDriverBufferImpl**)ppvObj;
846     FIXME("(%p,%p,%lx,%lx,%p,%p,%p): stub\n",This,pwfx,dwFlags,dwCardAddress,pdwcbBufferSize,ppbBuffer,ppvObj);
847
848     *ippdsdb = 0;
849     return DSERR_UNSUPPORTED;
850 }
851
852 static HRESULT WINAPI IDsDriverImpl_CreateSoundBuffer(PIDSDRIVER iface,
853                                                       LPWAVEFORMATEX pwfx,
854                                                       DWORD dwFlags,
855                                                       DWORD dwCardAddress,
856                                                       LPDWORD pdwcbBufferSize,
857                                                       LPBYTE *ppbBuffer,
858                                                       LPVOID *ppvObj)
859 {
860     TRACE("(%p,%p,%lx,%lx,%p,%p,%p)\n",iface,pwfx,dwFlags,dwCardAddress,pdwcbBufferSize,ppbBuffer,ppvObj);
861
862     if (dwFlags & DSBCAPS_PRIMARYBUFFER)
863         return DSD_CreatePrimaryBuffer(iface,pwfx,dwFlags,dwCardAddress,pdwcbBufferSize,ppbBuffer,ppvObj);
864
865     return DSD_CreateSecondaryBuffer(iface,pwfx,dwFlags,dwCardAddress,pdwcbBufferSize,ppbBuffer,ppvObj);
866 }
867
868 static HRESULT WINAPI IDsDriverImpl_DuplicateSoundBuffer(PIDSDRIVER iface,
869                                                          PIDSDRIVERBUFFER pBuffer,
870                                                          LPVOID *ppvObj)
871 {
872     /* IDsDriverImpl *This = (IDsDriverImpl *)iface; */
873     TRACE("(%p,%p): stub\n",iface,pBuffer);
874     return DSERR_INVALIDCALL;
875 }
876
877 static IDsDriverVtbl dsdvt =
878 {
879     IDsDriverImpl_QueryInterface,
880     IDsDriverImpl_AddRef,
881     IDsDriverImpl_Release,
882     IDsDriverImpl_GetDriverDesc,
883     IDsDriverImpl_Open,
884     IDsDriverImpl_Close,
885     IDsDriverImpl_GetCaps,
886     IDsDriverImpl_CreateSoundBuffer,
887     IDsDriverImpl_DuplicateSoundBuffer
888 };
889
890 static HRESULT WINAPI IDsDriverPropertySetImpl_Create(
891     IDsDriverBufferImpl * dsdb,
892     IDsDriverPropertySetImpl **pdsdps)
893 {
894     IDsDriverPropertySetImpl * dsdps;
895     TRACE("(%p,%p)\n",dsdb,pdsdps);
896
897     dsdps = (IDsDriverPropertySetImpl*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(dsdps));
898     if (dsdps == NULL) {
899         WARN("out of memory\n");
900         return DSERR_OUTOFMEMORY;
901     }
902
903     dsdps->ref = 0;
904     dsdps->lpVtbl = &dsdpsvt;
905     dsdps->buffer = dsdb;
906     dsdb->property_set = dsdps;
907     IDsDriverBuffer_AddRef((PIDSDRIVER)dsdb);
908
909     *pdsdps = dsdps;
910     return DS_OK;
911 }
912
913 static HRESULT WINAPI IDsDriverNotifyImpl_Create(
914     IDsDriverBufferImpl * dsdb,
915     IDsDriverNotifyImpl **pdsdn)
916 {
917     IDsDriverNotifyImpl * dsdn;
918     TRACE("(%p,%p)\n",dsdb,pdsdn);
919
920     dsdn = (IDsDriverNotifyImpl*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(dsdn));
921
922     if (dsdn == NULL) {
923         WARN("out of memory\n");
924         return DSERR_OUTOFMEMORY;
925     }
926
927     dsdn->ref = 0;
928     dsdn->lpVtbl = &dsdnvt;
929     dsdn->buffer = dsdb;
930     dsdb->notify = dsdn;
931     IDsDriverBuffer_AddRef((PIDSDRIVER)dsdb);
932
933     *pdsdn = dsdn;
934     return DS_OK;
935 }
936
937 DWORD wodDsCreate(UINT wDevID, PIDSDRIVER* drv)
938 {
939     IDsDriverImpl** idrv = (IDsDriverImpl**)drv;
940     TRACE("(%d,%p)\n",wDevID,drv);
941
942     /* the HAL isn't much better than the HEL if we can't do mmap() */
943     if (!(WOutDev[wDevID].ossdev->duplex_out_caps.dwSupport & WAVECAPS_DIRECTSOUND)) {
944         ERR("DirectSound flag not set\n");
945         MESSAGE("This sound card's driver does not support direct access\n");
946         MESSAGE("The (slower) DirectSound HEL mode will be used instead.\n");
947         return MMSYSERR_NOTSUPPORTED;
948     }
949
950     *idrv = (IDsDriverImpl*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(IDsDriverImpl));
951     if (!*idrv)
952         return MMSYSERR_NOMEM;
953     (*idrv)->lpVtbl          = &dsdvt;
954     (*idrv)->ref             = 1;
955     (*idrv)->wDevID          = wDevID;
956     (*idrv)->primary         = NULL;
957     (*idrv)->nrofsecondaries = 0;
958     (*idrv)->secondaries     = NULL;
959
960     return MMSYSERR_NOERROR;
961 }
962
963 DWORD wodDsDesc(UINT wDevID, PDSDRIVERDESC desc)
964 {
965     TRACE("(%d,%p)\n",wDevID,desc);
966     memcpy(desc, &(WOutDev[wDevID].ossdev->ds_desc), sizeof(DSDRIVERDESC));
967     return MMSYSERR_NOERROR;
968 }
969
970 #endif /* HAVE_OSS */